提问者:小点点

检查是否有任何文档匹配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)时,它会记录一个查询,但我想要的是文档而不是查询。

提前谢谢!


共2个答案

匿名用户

.findone()返回必须执行的查询,然后结果将异步产生。

基本上,您必须调用.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 = 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))

试试这个!