DerJP DerJP - 1 year ago 160
Node.js Question

Mongoose - Query latest document

This seems like such a basic question, but I can't find an answer to it.

I want to query for the latest document in my database. I wrote following function for it but it doesn't return the latest entry, instead it just returns the first one in the db. I tried find() instead of findOne() but it returned an object inside an array which isn't what I want. Is there a native mongoose function that returns the latest document in form of an object?

const getLatestRound = module.exports.getLatestRound = function(callback){
SmallHistory.findOne().limit(1).sort({ date: -1 }).exec((err, data) => {
if(err) {
callback(new Error('Error quering SmallHistory (getLatestRound())'));
return;
}
if(data) {
callback(null, data);
return;
}
});
}


Pls don't downvote :( Thanks

Answer Source

sort() and limit() are in the wrong order; you're limiting BEFORE your sort backward. Change it to:

SmallHistory.findOne().sort({ date: -1 }).limit(1).exec((err, data) 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download