简体   繁体   中英

How can I update a MongoDB collection using a JS/JSON object?

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.

Based on this answer

you can accomplish it by removing the brackets around data:

$set: data,
$currentDate: {
    "lastModified": true
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM