How to fetch next and previous item of the current one with Mongoose

后端 未结 2 1624
南方客
南方客 2020-12-15 11:25

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

相关标签:
2条回答
  • 2020-12-15 11:53

    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:

    1. If you don't use mongodb ObjectId above code will not work for you, but you can still use postDate instead of id and current post postDate instead of curId.
    2. 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.
    3. I am not familiar with mongoose, so above scripts is mongodb shell scripts.
    0 讨论(0)
  • 2020-12-15 11:55

    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)
    
    0 讨论(0)
提交回复
热议问题