猫鼬-查询最新文件 [英] Mongoose - Query latest document
问题描述
这似乎是一个基本问题,但我找不到答案.
This seems like such a basic question, but I can't find an answer to it.
我想查询数据库中的最新文档.我为此编写了以下函数,但它不返回最新条目,而是仅返回数据库中的第一个条目.我尝试使用find()而不是findOne(),但是它在数组中返回了一个我不想要的对象.是否有一个本地的mongoose函数以对象的形式返回最新文档?
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;
}
});
}
请不要投票:(谢谢
推荐答案
sort()
和limit()
的顺序错误;在进行反向排序之前,您要先进行限制.更改为:
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)
这篇关于猫鼬-查询最新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!