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

151
Vistas
How do I partially update a nested schema in mongoose?

EDIT: After trying many different approaches i found a working solution that maps any object to a format that mongoose understands. See solution here: https://stackoverflow.com/a/69547021/17426304

const updateNestedObjectParser = (nestedUpdateObject) => {
    const final = {

    }
    Object.keys(nestedUpdateObject).forEach(k => {
        if (typeof nestedUpdateObject[k] === 'object' && !Array.isArray(nestedUpdateObject[k])) {
            const res = updateNestedObjectParser(nestedUpdateObject[k])
            Object.keys(res).forEach(a => {
                final[`${k}.${a}`] = res[a]
            })
        }
        else
            final[k] = nestedUpdateObject[k]
    })
    return final
}

ORIGINAL QUESTION:

I have a mongoose structure of

    ChildSchema = {
      childProperty: String,
      childProperty2: String
    }

    MainSchema = {
      mainProperty: String,
      mainProperty2: String,
      child: childSchema
    }

In my update function I want to pass a partial object of mainSchema and only update the properties I pass to the function. This works fine for direct properties on my mainSchema but not on my childSchema. It overwrites the whole child property with the partial object given by my request.

So my update object looks something like this

const updates = {
   child: {
      childProperty2: 'Example2'
   }
}

How can I only update the childProperty2 without deleting the childProperty? In this example it would be easy to just update every property alone but the real world objects are much bigger and can be nested into multiple levels.

I tried to use destructuring but it does not seem to work

const example = MainSchema.findOne({_id})
if (updates.child) example.child = {...example.child, ...updates.child} // Does not work

Is there a solution to that in mongoose (6.0)?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Change your code like this:

const updates = {
  "child.childProperty2": 'Example2'
}
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