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 querying SmallHistory (getLatestRound())'));
return;
}
if(data) {
callback(null, data);
return;
}
});
}
Pls don't downvote :( Thanks
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.