MongoDB Node findone如何处理无结果? [英] MongoDB Node findone how to handle no results?
问题描述
我在节点上使用npm mongodb
驱动程序.
Im using the npm mongodb
driver with node.
我有
collection.findOne({query}, function(err, result) {
//do something
}
问题是说我没有任何结果,无论是否找到结果,err
仍然是null
.我怎么知道查询没有找到结果?
The problem is say I dont have any results, err
is still null
whether I find a result or don't. How would I know that there were no results found with the query?
我也尝试过
info = collection.findOne(....
但是info
只是undefined
(它看起来是异步的,所以我不认为这是要走的路.)
But the info
is just undefined
(it looked asynchronous so I didn't think it was the way to go anyway..)
推荐答案
未找到任何记录都不是错误条件,因此您要查找的是result
中缺少值.由于任何匹配的文档将始终是真实的",因此您可以简单地使用简单的if (result)
检查.例如,
Not finding any records isn't an error condition, so what you want to look for is the lack of a value in result
. Since any matching documents will always be "truthy", you can simply use a simple if (result)
check. E.g.,
collection.findOne({query}, function(err, result) {
if (err) { /* handle err */ }
if (result) {
// we have a result
} else {
// we don't
}
}
这篇关于MongoDB Node findone如何处理无结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!