I made an review app with Express and Mongoose. I have an review model like below:
var mongoose = require('mongoose');
var ReviewSchema = mongoose.Schema({
title: String,
description: String,
rating: Number
}, {
timestamps: true
}
);
module.exports = mongoose.model('Review', ReviewSchema);
In my controller I just get all reviews list as below. But now I want to get a list with 10 recently reviews & sort by (orderby timestamps). How can I do it with mongoose? Please help me! I am a newbie with NodeJS and Mongodb.
exports.findAll = function(req, res) {
console.log("Fetching Review...")
// Retrieve and return all reviews from the database.
Review.find(function(err, reviews){
if(err) {
console.log(err);
res.status(500).send({message: "Some error occurred while retrieving Review."});
} else {
res.send(reviews);
}
});
};
Thanks you so much
The limit() method in Mongoose is used to specify the number or a maximum number of documents to return from a query.
Mongoose is built untop of mongodb driver, the mongodb driver is more low level. Mongoose provides that easy abstraction to easily define a schema and query. But on the perfomance side Mongdb Driver is best. Save this answer.
It's basically there to ensure the strings you save through the schema are properly trimmed.
save() is a method on a Mongoose document. The save() method is asynchronous, so it returns a promise that you can await on.
This should work for you:
Review.find()
.sort({_id: -1})
.limit(10)
.then(reviews => {
console.log(reviews)
});
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