【问题标题】:Why does console.log return empty array in when using find method in mongoose?为什么console.log在mongoose中使用find方法时返回空数组?
【发布时间】:2020-08-26 19:30:00
【问题描述】:

我是后端开发新手。我正在尝试检查集合中是否已经存在现有用户,如果没有,则控制台日志“否”。我在“const b”中没有指示的数据,但不是“否”,而是在终端中不断得到空数组。

const b = {email: "xxx@mail.ru", password: "wwww"}
MyModel.find(b)
    .then(exUs =>{
        if(exUs){
            console.log(exUs)
        } else {
            console.log("no")
        }          
    })

【问题讨论】:

    标签: node.js mongodb asynchronous mongoose backend


    【解决方案1】:

    find 总是返回一个 cursor(如果没有文档,它可以是空的 []),所以你的 if 条件将永远为真,如果有零个文档,它将打印空数组 [](返回光标从不为空)。

    const b = {email: "xxx@mail.ru", password: "wwww"}
    MyModel.find(b)
        .then(exUs =>{
            if(exUs){ // this always returns true even if there are no docs as empty array[]
                console.log(exUs)
            } else {
                console.log("no")
            }          
        })
    

    你应该怎么做?

    这个

    const b = {email: "xxx@mail.ru", password: "wwww"}
    MyModel.find(b)
        .then(exUs =>{
    
            if(exUs.length>0){
                console.log(exUs)
            } else {
                console.log("no")
            }          
        })
    

    或者您可以使用findOne,如果没有找到文档,它将返回null,如果存在第一个文档,那么您的代码将变为

    const b = {email: "xxx@mail.ru", password: "wwww"}
    MyModel.findOne(b)
        .then(exUs =>{
            if(exUs){// checks for null here now
                console.log(exUs)
            } else { 
                console.log("no")
            }          
        })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-04
      • 2020-01-17
      • 2019-10-27
      • 1970-01-01
      • 1970-01-01
      • 2013-01-17
      相关资源
      最近更新 更多