user7201227 user7201227 - 12 days ago 4
Node.js Question

Retrieve last mongodb entry in nodejs

Hi I am new at Nodejs and mongodb. Need help to retrieve last record from my collection. I have this code right now`

db.collection('bbb1collection', function(err, collection) {
collection.find({}).sort({_id:-1}).limit(1).toArray(function(err, results) {
path = results;
console.log(results);


}

Answer

Check out this:

db.collection('bbb1collection', function(err, collection) {
  collection
    .find()
    .sort({$natural: -1})
    .limit(1)
    .next()
    .then(
      function(doc) {
        console.log(doc);
      },
      function(err) {
        console.log('Error:', err);
      }
    );
});

read about $natural here

Comments