【问题标题】:What does findOne() return exactly in mongoosefindOne() 在猫鼬中准确返回什么
【发布时间】:2016-07-12 21:51:44
【问题描述】:

你传入一个回调:

function(err, found) {

if(err) 
// checks to see if there was an error

else if (found)
// checks if the document exists

}

“立即”执行查询。这是检查文档是否存在的正确方法吗?如何判断文档是否存在?如何判断执行查询是否出错(假设在数据库返回结果之前连接已丢失)。我只是有点困惑,不胜感激。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    你所拥有的一切都会好起来的。

    如果有错误,你会想抛出错误。

    如果查询返回一个文档,found 将默认为 true。

    然后您可以继续在第二个 if 语句中使用找到的对象。

    查看查询是否成功但未找到用户:

    function(err, found) {
    
        if(err){
            throw err;
        }
    
        if(found){
            console.log(JSON.stringify(found));
        }else{
            console.log('The query was successful, but nothing was found');
        }
    }
    

    【讨论】:

    • 如果查询没有返回文档怎么办?它会默认为false吗?空?
    • 您可以在 if (found) 之后使用 else 语句来捕捉它。我会在我的回答中告诉你。
    猜你喜欢
    • 1970-01-01
    • 2019-03-25
    • 2019-02-13
    • 1970-01-01
    • 2021-09-18
    • 2020-02-03
    • 1970-01-01
    • 2019-03-24
    • 2021-09-03
    相关资源
    最近更新 更多