这一定是个愚蠢的问题,但我已经把头撞在墙上已经够久了。
简短版本:我有一个查询,它在 Mongo 控制台中按预期返回结果,但在通过 Mongo NodeJS 包使用时不返回结果(或错误)。
var weatherCacheQuery = {
'location': {
'$near': {
'$geometry': {
type: 'Point',
coordinates: [location.coordinates[0], location.coordinates[1]]
},
'$maxDistance': 50000
}
},
'retrieved': {
'$gte': moment().subtract(2, 'hours').toDate()
}
};
this.db.collection('weather').findOne(
weatherCacheQuery,
function(err, doc) {
console.log(JSON.stringify(err));
console.log(JSON.stringify(doc));
}
});
如您所见,没有什么过于复杂的。
如果我转储查询对象并将其粘贴到 Mongo 控制台中的 findOne 查询中,它会返回一个看起来完全符合预期的结果。但在 JS 中,两个 console.log() 返回 null。
更奇怪的是,具有相同查询的 find() 确实返回结果,但我无法查看结果,因为 JSON.stringify() 提示它是循环的。
有人能指出我做错的无疑荒谬的事情吗?
最佳答案
.findOne
对于 Node MongoDB 驱动程序需要三个参数,并且它们似乎都不是可选的。尝试:
this.db.collection('weather').findOne(
weatherCacheQuery, {},
function(err, doc) {
console.log(JSON.stringify(err));
console.log(JSON.stringify(doc));
}
});
您还可以使用 Promise 进行尝试,将 .then
链接到 .then
并将回调传递给它。
文档还说 .findOne
已弃用并可以使用。
find().limit(1).next
您可以将回调传递给它。
关于node.js - .findOne 未将结果传递给回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33875443/