0

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.

scubnoob
  • 27
  • 4

2 Answers2

0

Can you try this?

app.get("/pp", function (req, res) {
  PPOverTime.find()
    .limit(30)
    .sort({ _id: -1 })
    .then(results => {
      console.log(results)
    })
    .catch(error => console.error(error))
}
raga
  • 899
  • 10
  • 14
0

Thanks guys, here's how I did it.

// limit to returning only the last 20 entries
app.get("/pp", function (req, res) {
  let q = PPOverTime.find().limit(20).sort({ _id: 1 });
  q.exec(function (err, data) {
    res.send(data);
  });
});
scubnoob
  • 27
  • 4
  • I feel exec is an old way of doing using callbacks. [then and catch] i.e Promises helps in better code readability. – raga Aug 24 '20 at 02:18