0

I have a MongoDB collection that I'm looking to update. At the moment, I can only update it if I specifically set which values I want to update - for example:

  $set: {someVariable: someValue}

I would like to update using an object - so for instance if I had:

   data = {someVariable1: someValue, someVariable2: someValue}

and I passed it into the $set parameter, it should update those parameters.

Is there a way of doing this? At the moment if I just pass that data into the $set parameter, it adds on an extra value like so:

"_id" : "xxxxxxxxxx",
"someVariable1": "someValue", 
"someVariable2": "someValue",
"data" : {
    "someVariable1": "someValue", 
    "someVariable2": "someValue"
}

Here's my code snippet:

db.collection('test').updateOne(
        {_id: id},
        {
            $set: {
                data
            },
            $currentDate: {
                "lastModified": true
            }
        }, (err, result) => {
            assert.equal(err, null);
            callback(null, result);
        }
    )

where data is as above.

This is in Node.js by the way.

Many Thanks.

xn139
  • 375
  • 1
  • 4
  • 16

1 Answers1

0

Based on this answer

you can accomplish it by removing the brackets around data:

$set: data,
$currentDate: {
    "lastModified": true
}
Community
  • 1
  • 1