【问题标题】:Checking if there is any Document matching a certain condition in Mongoose (JavaScript)在 Mongoose (JavaScript) 中检查是否有任何符合特定条件的文档
【发布时间】:2020-09-08 17:41:33
【问题描述】:

所以基本上我想遍历文档并使用 .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) 时,它会记录一个查询,但我想要的是文档而不是查询。

提前致谢!

【问题讨论】:

  • 试试((await ExampleModel.findOne({name: "randomName" }).exec()) !== null)
  • 你需要 chaning 然后像这样赶上尝试doc.then(result => console.log(result)).catch(error => console.log(error))

标签: javascript node.js mongodb mongoose


【解决方案1】:

.findOne()返回Query,必须执行,然后结果异步出来。

基本上,你必须调用.exec(),然后等待返回的promise:

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()

【讨论】:

  • 感谢您回答我!只有一个问题,.then 方法会记录“Promise { }”。
  • 我很确定它不会。你确定,你的代码是一样的吗?
  • 你不需要.then() 的结果,你宁愿提供回调作为参数,-见Promises
  • 是的,完全一样,除了变量名和其他东西,但它的核心是一样的。如果我在 ExampleModel 后面放了一个等待它会给出一个错误,像 await 之类的东西只适用于异步函数或类似的东西。
  • 是的,await 只能在async 上下文中使用,即直接在async function 内部使用(参见MDN
【解决方案2】:
//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))

试试这个!

【讨论】:

    猜你喜欢
    • 2022-08-03
    • 1970-01-01
    • 2012-04-01
    • 2014-01-14
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多