MongoDB节点findone如何处理没有结果?
我使用节点的npm mongodb
驱动程序。
我有
collection.findOne({query}, function(err, result) { //do something }
问题是说我没有任何结果, err
仍是null
无论我find一个结果或不。 我怎么知道在查询中找不到结果?
我也试过了
info = collection.findOne(....
但info
只是undefined
(它看起来是asynchronous的,所以我不认为这是去的方式。)
没有find任何logging不是一个错误条件,所以你想要的是缺乏result
的价值。 由于任何匹配的文件将始终是“truthy”,您可以简单地使用一个简单的if (result)
检查。 例如,
collection.findOne({query}, function(err, result) { if (err) { /* handle err */ } if (result) { // we have a result } else { // we don't } }
以下所有答案都是过时的。 findOne已被弃用 。 最新的2.1文档build议使用
find(query).limit(1).next(function(err, doc){ // handle data })
简单地说:
collection.findOne({query}, function(err, result) { if (!result) { // Resolve your query here } }
如果结果为null,那么mongo没有find与您的查询匹配的文档。 已经尝试从mongo shell查询?
collection.findOne({query}, function(err, result) { if (err) { /* handle err */ } if (result.length === 0) { // we don't have result } }