Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Javascript 

Mongoose FindOneAndUpdate an embedded object and return parent

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({
  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.


Possibly Related Threads...
Thread / Author Replies Views Last Post
by InvictusProMar 23, 2024 07:56 AM 0 181 Mar 23, 2024 07:56 AM
Last Post: InvictusPro
[Javascript]  by bevcMar 25, 2022 02:34 AM 5 218 Mar 25, 2022 02:34 AM
Last Post: bevc
[Javascript]  by bevcDec 27, 2021 01:00 AM 4 185 Dec 27, 2021 01:00 AM
Last Post: bevc