Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

152
Visualizações
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 Respostas
Responde à pergunta

0

Change your code like this:

const updates = {
  "child.childProperty2": 'Example2'
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda