Skip to content
Advertisement

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

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?

Advertisement

Answer

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 })
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement