Feb 5, 2020 01:58 AM
(This post was last modified: Feb 5, 2020 04:27 AM by bevc.)
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.....
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:
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.....
Dunno why it works (what that '$' is doing in 'children.$.childTitle'), but it do.
Code
const parentSchema = new mongoose.Schema({
name: {
type: String
},
...
children: [{
childTitle: {
type: String,
max: 150,
required: true
},
...
}],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 }
const update = { childTitle: req.body.childTitle } // think the prob is with the 'childTitle' part here
let parent = await Parent.findOneAndUpdate(filter, update, {
new: true,
runValidators: true
})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.

