简体   繁体   中英

Checking if there is any Document matching a certain condition in Mongoose (JavaScript)

So basically I want to run through the documents and with the .find method check if there is a Document that meets the condition, like this:

//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!")

The problem with this is that it doesn't work and when I do console.log(doc) it logs a Query but I want the document and not a Query.

Thanks in advance!

.findOne() returns Query , which has to be executed, and then the results will come asynchronously.

Basically, you have to call .exec() and then await the returned 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!")
  })

… or (using async / await syntax):

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

Try this out!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM