![]() |
|
[Javascript] Mongoose FindOneAndUpdate an embedded object and return parent - Printable Version +- Hack Forums (https://hackforums.net) +-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444) +--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151) +---- Forum: Web Development (https://hackforums.net/forumdisplay.php?fid=183) +---- Thread: [Javascript] Mongoose FindOneAndUpdate an embedded object and return parent (/showthread.php?tid=6046841) |
Mongoose FindOneAndUpdate an embedded object and return parent - bevc - Feb 5, 2020 I'm having problems with a mongoose/mongo query. I want to find and update a subdocument that's embedded in a parent document in an array, and then return the parent document. So my schema is like this..... Code const parentSchema = new mongoose.Schema({and so on. Based on an answer I found on stackoverflow, I'm able to retrieve the entire parent document using the id of the subdocument (which seems like a query-saver), but then I can't figure out how to update the subdocument. I checked the documents for mongoose and tried to follow their example, but it doesn't update my subdocument. This is my code: Code const filter = { 'child._id': req.body.childId }It doesn't work, it returns the correct parent document but it doesn't update the subdocument. I strongly suspect it's something to do with my 'update' variable query but I'm buggered if I know what (I've tried it with and without '$set'). Could anyone help point me in the right direction please? Thanks. For info, I seem to have got this figured out by just cribbing another stackoverflow answer. This query gets me where I need to be..... Code await Parent.findOneAndUpdate({ _id: req.body.parentId, "child._id": req.body.childId }, { "children.$.childTitle": req.body.childTitle })Dunno why it works (what that '$' is doing in 'children.$.childTitle'), but it do. |