Home > database >  Mongoose: edit deeply nested (recursively) subdocument
Mongoose: edit deeply nested (recursively) subdocument

Time:11-28

I have a recursively nested subdocuments (arrays), looks generally like:

parent:{
    children:[{
        field,
        children:[{
            field,
            children:[{
                ...
                }]
            },
            {
            field,
            children:[{
                ...
                }]
            },
        ...]
    }
}

Meaning every children subdocument may have another nested children subdocuments.

I'm trying to edit a subdocument (let's call it "child"). For example, I want to edit the child at level 3. This means I need to go down 3 levels of children, access the child and save the document (parent).

What I'm doing now is to send the level to the function, along with the information I want to add to the child. I find the document (findOne to the parent's Id), go down the levels, attempt to edit the child, and finally save the document:

await parentModel.findOne({'_id': parentId}).populate(/*population needed for the information*/)
  .exec().then(async (result)=>{
    let children = result.children;
    for (let i=0; i<level;i  ){
      children = children.children;
    }
    children.push(child); //in my specific case I simply push the child to the children one level above

    await result.save((e,doc)=>{...})

What happens is that I do see that children.push(child) is successful, but the document does not save it (although the save function is successful as well).

I assume it has something to do with the fact that I take children locally (let children...), but I'm not sure if that's true, so I'm seeking advice.

CodePudding user response:

when you change a nested array you have to "tell" to mongoose that is changed, because by default it not recognize it.

You can do this using markModified('fieldName').

example:

parent ---> a mongooose doc
parent.child.push({new child object});
parent.markModified('child);
parent.save();
  • Related