[英]Checking if there is any Document matching a certain condition in Mongoose (JavaScript)
所以基本上我想遍历文档并使用 .find 方法检查是否有满足条件的文档,如下所示:
//example model
const example = new ExampleModel ({
exampleName : "randomName",
exampleValue : 0
})
const doc = ExampleModel.findOne( {name : "randomName"} )
if (doc) console.log("There is a Document with that name!")
问题在于它不起作用,当我执行console.log(doc)
它会记录一个查询,但我想要文档而不是查询。
提前致谢!
.findOne()
返回Query
,它必须被执行,然后结果将异步出现。
基本上,您必须调用.exec()
然后等待返回的承诺:
const example = new ExampleModel({
exampleName : "randomName",
exampleValue : 0,
})
ExampleModel
.findOne({ name : "randomName" })
.exec()
.then((doc) => {
if (doc) console.log("There is a Document with that name!")
})
... 或(使用async
/ await
语法):
async function main() {
const example = new ExampleModel({
exampleName : "randomName",
exampleValue : 0,
})
const doc = await ExampleModel.findOne({ name : "randomName" }).exec()
if (doc) console.log("There is a Document with that name!")
}
main()
//example model
const example = new ExampleModel ({
exampleName : "randomName",
exampleValue : 0
})
ExampleModel.findOne( {name : "randomName"} )
.then (doc => {
if (doc) console.log("There is a Document with that name!")
})
.catch(err => console.log(err))
试试这个!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.