Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

node.js - I will like to return the previous object and the next object of a matching object id in node

Please i am new to node js and MongoDB. When i want to retrieve a post by id, i want to be able to retrieve the previous post and next post also. this is my post, it only retrieves the current post by 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,
      });
    });
};

I currently receive the object with the id like this which is fine.

{
    "_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
}

But i will love to receive the object of the current id, the previous object and the next object. something like this.

[{
    "_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
}]
question from:https://stackoverflow.com/questions/65848518/i-will-like-to-return-the-previous-object-and-the-next-object-of-a-matching-obje

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since its a UUID, this approach might help you..

  • $sort to sort the documents by asc
  • $group and $unwind to get the index
  • $facet to categorize the incoming data into current and allDocs
  • We know current is only one object, so we do $unwind to deconstruct the array
  • We already know the index, so we use $filter to get prev, current and next using index
  • $unwind to deconstruct the array
  • $replaceRoot to make the objects to the root

Here is the script

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" } }
])

Working Mongo playground

There are many ways to do this, this is one of the way. If you feel you have a lot of document, then try to avoid $unwind which is expensive, in that case you can try using createdDate instead of index


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...