簡體   English   中英

檢查 Mongoose (JavaScript) 中是否有符合特定條件的文檔

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM