How can I sort and limit with Mongoose
Asked Answered
B

3

8

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

Bottommost answered 25/8, 2018 at 5:56 Comment(2)
Try this Review.find({}).sort({ createdAt: 1 }).limit(10)Kowtow
It's not work, Anthony WinzletBottommost
R
24

This should work for you:

Review.find()
  .sort({_id: -1})
  .limit(10)
  .then(reviews => {
    console.log(reviews)
  });
Rudder answered 25/8, 2018 at 6:41 Comment(1)
Awesome. Thanks. You should mark the answer so hopefully it could help others.Rudder
M
6

you can try like this :

Review.find({}, function(err,reviews){}).sort({_id: -1}).limit(10);
Mythopoeia answered 25/8, 2018 at 6:28 Comment(0)
S
0
  //note that the req param is not used so I set it to _
module.exports.findAll = async(_,res) => {
   try{
     const someReviews = await Reviews.find({});
     console.log(someReviews);
     .sort({"createdAt": -1})//-1 from newest to oldest 1 otherwise
     .limit(10);
     res.status(200).send(someReviews);
   }catch(e){
      console.log({error: e});
      res.status(500).send({error: `Could not fetch reviews`};
   }
}
Southworth answered 30/7 at 12:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.