首页 文章

查询MongoDB返回5条最新记录(Mongoose框架)[重复]

提问于
浏览
0

这个问题在这里已有答案:

我正在尝试查询我的MongoDB以返回最近的5条记录 . 我有Mongoose作为我的框架并使用Node.js作为我的服务器 . 我有这个模型:

var Schema = mongoose.Schema;
var uGardenDataModel = new Schema({
temp: String,
humidity: String,
soilMoisture: String,
light: String,
timestamp: Date,
});
// Create model
var uGardenData = mongoose.model('UGarden', uGardenDataModel);

我查询数据库的功能在这里:

function getChartData(res){
//uGardenData.find({},{sort: {_id:-1}},limit: 5, function(err, post){
    uGardenData.find({sort:{'timestamp': -1}},{limit: 5}, function(err, post){
    if(err){
        res.send({success: false});
        console.log('failed');
    } else {
        res.send({data:post,success:true});
        console.log('success');
    }
})
}

我相信我的查询语法错了 . 一旦我使用浏览器的控制台发出了对该函数的HTTP请求,我得到:data:Array(0),success:true

尽管在数据库中有记录,但看起来它没有返回任何数据 . 有什么想法吗?

1 回答

  • 0

    是的,你正在错误地调用 find . 根据手册,find采用一个必需参数和3个可选参数 . 排序和限制是options参数的一部分,即第3个参数 . 所以你需要仍然传递前两个,虽然是空的 .

    试试以下电话:

    uGardenData.find({}, null, {sort:{'timestamp': -1},limit: 5}, function(err, post){
    

相关问题