Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
Mongoose: edit deeply nested (recursively) subdocument

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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();
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!