How can I sort and limit with Mongoose

10,201

Solution 1

This should work for you:

Review.find()
  .sort({_id: -1})
  .limit(10)
  .then(reviews => {
    console.log(reviews)
  });

Solution 2

you can try like this :

Review.find({}, function(err,reviews){}).sort({_id: -1}).limit(10);
Share:
10,201

Related videos on Youtube

cauchuyennhocuatoi
Author by

cauchuyennhocuatoi

Updated on September 15, 2022

Comments

  • cauchuyennhocuatoi
    cauchuyennhocuatoi over 1 year

    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

  • Akrion
    Akrion over 5 years
    Awesome. Thanks. You should mark the answer so hopefully it could help others.