Loïc V
Loïc V

Reputation: 635

Mongoose: update only undefined / unexisting properties and let existing unmodified

Let's say I have the following data in mongo:

{name: "peter", jobTitle: "engineer", id: 17, webs:[]} 

and I get more info from him so I want to update the not-existing properties:

new data:

{id:17, jobTitle: "gdkjd", phone:"+397373888348", mail:"[email protected]", webs:["one"],}

What I would love to achieve

{id:17, name: "peter", jobTitle: "engineer", phone:"+397373888348", mail:"[email protected]", webs:["one"]}

Is there a way to get this without checking individually which properties are already set?

Note: Specially complicated is the idea to add values to the array without overriding it. So less imagine my original array was:

webs: ["two", "three"]

So with this "nonbreaking update" i would expect the database to have this:

webs: ["two", "three", "one"]

Upvotes: 1

Views: 297

Answers (1)

Joe
Joe

Reputation: 28316

For non-array fields, you can get this behavior using the pipeline form of update with the $mergeObjects operator.

To handle some fields like arrays specially, assign those first. Something like:

newData={id:17, jobTitle: "gdkjd", phone:"+397373888348", mail:"[email protected]", webs:["one"]}

db.collection.update({id:newData.id},
                     [
                       {$set:{webs:{$concatArrays:[
                                     {$cond:[
                                         {$eq:[{$type:"$webs"},"array"]},
                                         "$webs",
                                         []
                                     ]},
                                   newData.webs
                       ]}}},
                       {$set:{newDoc:{$mergeObjects:[newData,"$$ROOT"]}}},
                       {$replaceRoot:{newRoot: "$newDoc"}}
                     ]
)

Upvotes: 1

Related Questions