I'm having trouble writing a callback for fetching the latest N records from a mongoDB collection. I'm creating an Express route called /pp that will return stuff in my DB. I used to just return everything in it, so something like:
app.get("/pp", function (req, res) {
PPOverTime.find({}, function (error, documents) {
res.send(documents);
});
});
(PPovertime is the name of my collection btw)
But I want to now take the last N records placed into the DB, which according to the Stack Overflow post linked above is accomplished via "db.foo.find().sort({_id:-1}).limit(30)" for last 30 entries, for example.
So where do I put the callback function to return the response? I tried:
app.get("/pp", function (req, res) {
PPOverTime.find()
.limit(30)
.sort({ _id: -1 }, function (error, documents) {
res.send(documents);
});
});
But this gives an error because the sort function can only take in one argument. I guess more generally how do I do this asynchronously if I have more than one function to run on a find() call? Thanks.