node.js MongoDB Node findone 如何处理没有结果?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10551313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:41:21  来源:igfitidea点击:

MongoDB Node findone how to handle no results?

node.jsmongodb

提问by Akshat

Im using the npm mongodbdriver with node.

我使用mongodb带有节点的 npm驱动程序。

I have

我有

collection.findOne({query}, function(err, result) {
    //do something
}

The problem is say I dont have any results, erris still nullwhether I find a result or don't. How would I know that there were no results found with the query?

问题是说我没有任何结果,err仍然null是我是否找到了结果。我怎么知道查询没有找到结果?

I've also tried

我也试过

info = collection.findOne(....

But the infois just undefined(it looked asynchronous so I didn't think it was the way to go anyway..)

info它只是undefined(它看起来是异步的,所以我不认为这是要走的路..)

回答by jmar777

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.,

找不到任何记录不是错误条件,因此您要查找的是result. 由于任何匹配的文档总是“真实的”,您可以简单地使用简单的if (result)检查。例如,

collection.findOne({query}, function(err, result) {
    if (err) { /* handle err */ }

    if (result) {
        // we have a result
    } else {
        // we don't
    }
}

回答by Stepan Yakovenko

All of these answers below are outdated. findOne is deprecated. Lastest 2.1 documentation proposes to use

以下所有这些答案都已过时。findOne 已弃用。最新 2.1 文档建议使用

find(query).limit(1).next(function(err, doc){
   // handle data
})

回答by sospedra

Simply as:

简单来说:

collection.findOne({query}, function(err, result) {
    if (!result) {
        // Resolve your query here
    }
}

回答by user2779653

nowadays - since node 8- you can do this inside an asyncfunction:

现在 - 从节点 8 开始- 您可以在async函数中执行此操作:

async function func() {
  try {
    const result = await db.collection('xxx').findOne({query});
    if (!result) {
      // no result
    } else {
      // do something with result
    }
  } catch (err) {
    // error occured
  }
}

回答by Martin

If result is null then mongo didn't find a document matching your query. Have tried the query from the mongo shell?

如果结果为空,则 mongo 未找到与您的查询匹配的文档。是否尝试过来自 mongo shell 的查询?

回答by parkerproject

collection.findOne({query}, function(err, result) {
   if (err) { /* handle err */ }

   if (result.length === 0) {
    // we don't have result
   }
}