[英]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.
我尝试使用find()而不是findOne(),但是它在数组中返回了一个我想要的对象。 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; sort()
和limit()
的顺序错误; you're limiting BEFORE your sort backward. 您必须先限制后退。 Change it to:
更改为:
SmallHistory.findOne().sort({ date: -1 }).limit(1).exec((err, data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.