为什么在猫鼬中使用 find 方法时 console.log 返回空数组?



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

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

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")
}          
})

相关内容

最新更新