How To Fetch Next And Previous Item Of The Current One With Mongoose
I have a blog. On the individual post page I want to display a link to the previous, and if there is one, next post published in the bottom. The link should be the title of the spe
Solution 1:
So let suppose you have schema like this:
{
_id,
text
}
I suppose that _id is mongo ObjectId, so we it contains post date and i can sort on it
Lets consider that i have opened current post with id equal to ObjectId( "43cc63093475061e3d95369d")
(instead of this i will use curId
) and i need to know next one and previous. Also lets consider that we need get all posts one by one ordered by created date descending:
Get next post you can like this:
db.posts.find({_id: {$gt: curId}}).sort({_id: 1 }).limit(1)
Get previous post you can like this:
db.posts.find({_id: {$lt: curId}}).sort({_id: -1 }).limit(1)
Few things:
- If you don't use mongodb
ObjectId
above code will not work for you, but you can still usepostDate
instead of id and current post postDate instead ofcurId
. - Take care about order when getting next/prev posts, to retrieve next post you need sort asc, to retrieve prev post you need sort desc.
- I am not familiar with mongoose, so above scripts is mongodb shell scripts.
Solution 2:
Find previous item:
Post.findOne({_id: {$lt: curId}}).sort({_id: -1}).exec(cb)
Find next item:
Post.findOne({_id: {$gt: curId}}).sort({_id: 1}).exec(cb)
Post a Comment for "How To Fetch Next And Previous Item Of The Current One With Mongoose"