Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort and limit with Mongoose

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

like image 655
cauchuyennhocuatoi Avatar asked Aug 25 '18 05:08

cauchuyennhocuatoi


People also ask

What is limit in Mongoose?

The limit() method in Mongoose is used to specify the number or a maximum number of documents to return from a query.

Which is better MongoDB or Mongoose?

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.

What does trim do in Mongoose?

It's basically there to ensure the strings you save through the schema are properly trimmed.

What is Save () in Mongoose?

save() is a method on a Mongoose document. The save() method is asynchronous, so it returns a promise that you can await on.


1 Answers

This should work for you:

Review.find()
  .sort({_id: -1})
  .limit(10)
  .then(reviews => {
    console.log(reviews)
  });
like image 142
Akrion Avatar answered Sep 24 '22 18:09

Akrion