2

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)?

niksan
  • 21
  • 3

1 Answers1

1

Change your code like this:

const updates = {
  "child.childProperty2": 'Example2'
}
NeNaD
  • 18,172
  • 8
  • 47
  • 89
  • Is there a more abstract method of doing this? This approach works but requires a giant amount of manual work since there are many places where I´d need to change this. So is there maybe a function to map any object to your given format? – niksan Nov 16 '21 at 09:29