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

150
Views
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 answers
Answer question

0

Change your code like this:

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