Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

131
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda