Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 我想返回节点中匹配对象id的上一个对象和下一个对象_Node.js_Database_Mongodb_Mongoose_Nosql - Fatal编程技术网

Node.js 我想返回节点中匹配对象id的上一个对象和下一个对象

Node.js 我想返回节点中匹配对象id的上一个对象和下一个对象,node.js,database,mongodb,mongoose,nosql,Node.js,Database,Mongodb,Mongoose,Nosql,请告诉我,我是新的节点js和MongoDB。 当我想通过id检索一篇文章时,我希望能够检索上一篇文章和下一篇文章。 这是我的帖子,它只按id检索当前帖子 Post.findById(req.params.postId) .then((existingpost) => { console.log(Post.find(req.params.postId)) if (existingpost) { res.send(existingpost);

请告诉我,我是新的节点js和MongoDB。 当我想通过id检索一篇文章时,我希望能够检索上一篇文章和下一篇文章。 这是我的帖子,它只按id检索当前帖子

Post.findById(req.params.postId)
    .then((existingpost) => {
        console.log(Post.find(req.params.postId))
      if (existingpost) {
        res.send(existingpost);
      }
      return res.status(404).send({
        message: "Post does not exist with id " + req.params.postId,
      });
    })
    .catch((err) => {
      if (err.kind === "ObjectId") {
        return res.status(404).send({
          message: "Post does not exist with id " + req.params.postId,
        });
      }
      return res.status(500).send({
        message:
          "Some error occurred while retrieving the post with postId " +
          req.params.postId,
      });
    });
};
我目前收到的对象id如下,这很好

{
    "_id": "6009f3e294d8a033402a76e7",
    "title": "Covid 19 in Italy",
    "author": "John Doe",
    "createdAt": "2021-01-21T21:36:34.514Z",
    "updatedAt": "2021-01-21T21:36:34.514Z",
    "__v": 0
}
但是我会喜欢接收当前id的对象、前一个对象和下一个对象。 像这样的

[{
    "_id": "3230g5e382d8a033402a76e7",
    "title": "Effect of Covid on the Economy",
    "author": "John Doe",
    "createdAt": "2021-01-21T21:36:34.514Z",
    "updatedAt": "2021-01-21T21:36:34.514Z",
    "__v": 0
},
{
    "_id": "6009f3e294d8a033402a76e7",
    "title": "Covid 19 in Italy",
    "author": "John Doe",
    "createdAt": "2021-01-21T21:36:34.514Z",
    "updatedAt": "2021-01-21T21:36:34.514Z",
    "__v": 0
},
{
    "_id": "4567hye294d8a033402a76e7",
    "title": "Life after Covid",
    "author": "John Doe",
    "createdAt": "2021-01-21T21:36:34.514Z",
    "updatedAt": "2021-01-21T21:36:34.514Z",
    "__v": 0
}]

我不确定有没有直接的方法,你可以试试聚合

使用UUID和CreatedAt:

  • $facet
    通过
    createdAt以升序排序后,获取
    all
    中的所有文档
  • $let
    定义变量
    状态
    ,包括起始文档和总文档
  • $cond
    检查输入uuid的索引是否为零,然后返回
    开始:0
    总计:2
    文档我们必须从所有数组中切片,否则获取当前索引并减去-1和
    总计:3
  • in
    start
    total


使用ObjectID:

  • 使用
    mongoose.Types.ObjectId
  • $facet
    用于分离结果
  • 首先,
    $match
    获取当前和下一个文档,
    $sort
    \u id
    按降序,
    $limit
    2
  • 其次,
    $match
    获取上一个文档,
    $sort
    \u id
    按降序,
    $limit
    1
  • $project
    使用
    $concatarray

由于它是UUID,这种方法可能会对您有所帮助

  • $sort
    按asc对文档进行排序
  • $group
    $unwind
    以获取索引
  • $facet
    将传入数据分类为
    current
    allDocs
  • 我们知道current只是一个对象,所以我们使用
    $unwind
    来解构数组
  • 我们已经知道索引,所以我们使用
    $filter
    使用索引获取上一个、当前和下一个
  • $unwind
    解构阵列
  • $replaceRoot
    将对象设置为根
这是剧本

db.collection.aggregate([
   $sort: { createdAt: 1 } },
  {
    $group: {
      _id: null,
      data: { $push: "$$ROOT"}
    }
  },
  { $unwind: { path: "$data", includeArrayIndex: "index" } },
  {
    $facet: {
      current: [
        { $match: { "data._id": "3230g5e382d8a033402a76e7" } }
      ],
      allDocs: [
        { $match: {} }
      ]
    }
  },
  {
    $unwind: "$current"
  },
  {
    $project: {
      docs: {
        $filter: {
          input: "$allDocs",
          cond: {
            $or: [
              { $eq: [ "$$this.index", { $subtract: [ "$current.index", 1 ] } ] },
              { $eq: [ "$$this.index", "$current.index" ] },
              { $eq: [ "$$this.index", { $add: [ "$current.index", 1 ] } ] }
            ]
          }
        }
      }
    }
  },
  { "$unwind": "$docs" },
  { "$replaceRoot": { "newRoot": "$docs.data" } }
])
工作


有很多方法可以做到这一点,这是其中之一。如果您觉得有很多文档,那么请尽量避免使用成本高昂的
$unwind
,在这种情况下,您可以尝试使用
createdDate
而不是index

这是ObjectId还是UUID?如果是UUID,你会如何比较!!O.O.可能是ObjectId,因为他是以字符串形式发布的,所以我提出了这个问题。我只是想建立索引或(可能还包括创建日期)。工作可能需要很长时间method@turivishal谢谢你的密码。上面的id不是结构化id,而是uuid。@turivishal I jsut发布了我的答案,因为他说这是uuid。取决于_id,两个答案都正确type@turivishal哇,这想法真不错
req.params.postId = mongoose.Types.ObjectId(req.params.postId);
Post.aggregate([
  {
    $facet: {
      first: [
        { $match: { _id: { $gte: req.params.postId } } },
        { $sort: { _id: 1 } },
        { $limit: 2 }
      ],
      second: [
        { $match: { _id: { $lt: req.params.postId } } },
        { $sort: { _id: -1 } },
        { $limit: 1 }
      ]
    }
  },
  { $project: { result: { $concatArrays: ["$first", "$second"] } } }
])
db.collection.aggregate([
   $sort: { createdAt: 1 } },
  {
    $group: {
      _id: null,
      data: { $push: "$$ROOT"}
    }
  },
  { $unwind: { path: "$data", includeArrayIndex: "index" } },
  {
    $facet: {
      current: [
        { $match: { "data._id": "3230g5e382d8a033402a76e7" } }
      ],
      allDocs: [
        { $match: {} }
      ]
    }
  },
  {
    $unwind: "$current"
  },
  {
    $project: {
      docs: {
        $filter: {
          input: "$allDocs",
          cond: {
            $or: [
              { $eq: [ "$$this.index", { $subtract: [ "$current.index", 1 ] } ] },
              { $eq: [ "$$this.index", "$current.index" ] },
              { $eq: [ "$$this.index", { $add: [ "$current.index", 1 ] } ] }
            ]
          }
        }
      }
    }
  },
  { "$unwind": "$docs" },
  { "$replaceRoot": { "newRoot": "$docs.data" } }
])