Home > OS >  Mongoose how to extract value from findOne() and use that to update value
Mongoose how to extract value from findOne() and use that to update value

Time:11-08

const flightNo = await FlightInfo.findOne({ "flightID": id }).select({ "flightNo": 1, "_id": 0 })
console.log(flightNo)
await FlightInfo.findOneAndUpdate({ "flightID": id }, { "gate": assignedGate })
await Gate.findOneAndUpdate({ "gate": assignedGate }, { "lastUseTime": currTime, "flightNo": flightNo })

And the console log shows flightNo as { flightNo: 'UA567' }

I want to use the flightNo "UA567" in findOneAndUpdate. But this function fails. How can I extract the string from the object?

CodePudding user response:

flightNo is an object which contains the field 'flightNo', you can access the value of that field by writing

console.log(flightNo.flightNo)

or you can write

const {flightNo} = await FlightInfo.findOne({ "flightID": id }).select({ "flightNo": 1, "_id": 0 })
console.log(flightNo)

and destructure that value from inside the object

Also findOneAndUpdate returns the document so you can just write:

const {flightNo}=await FlightInfo.findOneAndUpdate({ "flightID": id }, { "gate": assignedGate })
await Gate.findOneAndUpdate({ "gate": assignedGate }, { "lastUseTime": currTime, flightNo })
  • Related