charlotte zou
charlotte zou

Reputation: 27

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?

Upvotes: 0

Views: 89

Answers (1)

jessica-98
jessica-98

Reputation: 609

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

Upvotes: 1

Related Questions