2017-04-21 101 views
0

我有一個MongoDB集合,我正在更新。此刻,我只能更新它,如果我專門設置我想更新其值 - 例如:如何使用JS/JSON對象更新MongoDB集合?

$set: {someVariable: someValue} 

我想使用一個對象來更新 - 因此,舉例來說,如果我有:

data = {someVariable1: someValue, someVariable2: someValue} 

我把它傳入$set參數,它應該更新這些參數。

有沒有辦法做到這一點?在如果我只是通過這些數據爲$set參數的那一刻,它增加了對像這樣的額外價值:

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

這裏是我的代碼片段:

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

在數據如上。

這是在Node.js中的方式。

很多謝謝。

回答

0

基於this answer

可以通過刪除圍繞數據的括號完成它:

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

完美。謝謝。 – xn139