如何获取当前与Mongoose的下一个和上一个项目 [英] How to fetch next and previous item of the current one with Mongoose

查看:398
本文介绍了如何获取当前与Mongoose的下一个和上一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个博客。在单个帖子页面上,我想显示一个链接到上一个,如果有一个,下一个帖子发布在底部。链接应该是特定帖子的标题。



如何用Mongoose最简单的方法?



我当前的控制器如下所示:

  Post.findOne {slug:req.params.slug},(err,post ) - > 
res.renderblog / show.jade,本地人:标题:这篇文章,帖子:帖子

并且模式如下所示:

  PostSchema =新模式(
标题:
type:String
required:true
index:true
前导序列:String
body:String
slug:String
createdAt:Date
updatedAt:Date


解决方案

假设你有这样的模式:

  {
_id,
text
}

我认为_id是mongo ObjectId,所以我们包含发布日期,我可以排序它



让我们认为我已经打开了id等于 ObjectId(43cc63093475061e3d95369d)的当前帖子(而不是我会使用 curId ),我需要知道下一个和以前。还要让我们考虑,我们需要按创建日期降序排列所有帖子:



获取下一篇文章,您可以这样:

  db.posts.find({_ id:{$ gt:curId}})sort({_ id:1})。limit(1)

获取以前的帖子您可以这样:

  db.posts.find({_ id:{$ lt:curId}})sort({_ id:-1})。limit(1)

几件事:


  1. 如果不使用mongodb ObjectId 以上代码将无法为您服务,但您仍然可以使用 postDate 而不是id和当前post postDate而不是 curId

  2. 在下一个/上一个帖子时,请注意订单,以检索您需要排序的下一个帖子,以检索prev post你需要排序描述。

  3. 我不熟悉mongoose,所以上面的脚本是mongodb shell脚本。


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
)

解决方案

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.

这篇关于如何获取当前与Mongoose的下一个和上一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆