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
)
In Mongoose the “_v” field is the versionKey is a property set on each document when first created by Mongoose. This is a document inserted through the mongo shell in a collection and this key-value contains the internal revision of the document.24-Jun-2021.
The find() function is used to find particular data from the MongoDB database.
What is findById() in Mongoose? In MongoDB, all documents are unique because of the _id field or path that MongoDB uses to automatically create a new document. For this reason, finding a document is easy with Mongoose. To find a document using its _id field, we use the findById() function.
Mongoose | findOne() Function The findOne() function is used to find one document according to the condition. If multiple documents match the condition, then it returns the first document satisfying the condition.
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:
ObjectId
above code will not work for you, but you can still use postDate
instead of id and current post postDate instead of curId
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With