Jithesh Kt Jithesh Kt - 5 months ago 37
Node.js Question

Persist rest of the object when updating fields with $set- mongoose

Below is my collection structure :

"_id" : ObjectId("59c9e021af4886c9149a28c7"),
"userkey" : "r1Et2ZNdW",
"devicekey" : "12345",
"analog" : {
"4" : 458,
"6" : 448,
"7" : 100
"__v" : 0

My update code for the collection is :

DeviceModel.update({_id : device.id}, {$set : {"analog" : analog}}, function(err, doc){
if(err) throw err;
console.log("Device switches updated");

I want to update the one (or more) value of "analog" object. I may or may not have entire value of the "analog" collection. Which means most of the time I will be having just
{"7" : 200}
{"6" : 500}
...etc. If I use this in my above update code it works. But the problem is rest of the items in the object will be removed. That is, the "analog" object will become just
{"7" : 200}
. What change should I do to my update code to persist the rest of the Object.? or do I need to change my entire logic ?

Answer Source

You need to first flatten the analog variable object into another object with a property that uses the dot notation. This enables the $set operator to correctly update the embedded field denoted in the dot notation without updating/removing/affecting the other fields.

So, in your example you can go about this:

let setObject = {};
Object.keys(analog).forEach(function (key) {
    setObject[`analog.${key}`] = analog[key];

    { '_id': device.id }, 
    { '$set': setObject }, 
    function(err, doc) {
        if(err) throw err;
        console.log("Device switches updated");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download