0

I am trying to get the latest collection record from my MongoDB using mongoose.

My current code goes as follows:

ApiData.findOne(  
    (err, data) => {
        if (err) {
    //            res.status(200).send(err);
        }
        if (data) {  // Search could come back empty, so we should protect against sending nothing back
    //            res.status(200).send(data);
        console.log(data);

        } else {  // In case no kitten was found with the given query
    //            res.status(200).send("No kitten found");
        }
    }, { sort: { _id: -1 }, limit: 1 });

But this does not work in sorting the latest data, only shows the first record.

M Q
  • 233
  • 1
  • 4
  • 12

2 Answers2

2

To get latest added data :

ApiData.findOne({}).sort({date: -1}).exec(function(err, data) {
    if (err) {
    //            res.status(200).send(err);
        }
        if (data) {  // Search could come back empty, so we should protect against sending nothing back
    //            res.status(200).send(data);
        console.log(data);

        } else {  // In case no kitten was found with the given query
    //            res.status(200).send("No kitten found");
        }
});

To get all data just replace findone with find

wrangler
  • 3,454
  • 1
  • 19
  • 28
  • Hi, thanks for replying! I haven't tried this answer, because I ended up fixing it by adding .sort.({"_id": -1}) to the end of my code. – M Q Nov 08 '17 at 17:17
0

I found out my problem after searching Stackoverflow.

The problem was fixed by removing , { sort: { _id: -1 }, limit: 1 }); and adding .sort.({"_id": -1}) to the end of my closing brackets!

Thanks for trying to answer my problem guys!

M Q
  • 233
  • 1
  • 4
  • 12