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
489 views
in Technique[技术] by (71.8m points)

javascript - 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 specific post.

How do I do that the simplest way with Mongoose?

My current controller looks like this:

Post.findOne { slug : req.params.slug }, (err, post) ->
  res.render "blog/show.jade", locals: title: "This post", post: post

And the schema looks like this:

PostSchema = new Schema(
  title:
    type: String
    required: true
    index: true
  preamble: String
  body: String
  slug: String
  createdAt: Date
  updatedAt: Date
)
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.

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

...