MongoDB Node findone如何处理无结果? [英] MongoDB Node findone how to handle no results?

查看:236
本文介绍了MongoDB Node findone如何处理无结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在节点上使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆