2

i am using node.js mongodb native driver.

Let's say I have a mongodb collection called tasks , each task looks like

{date:'29th jan', desc:'xxx', status:'incomplete'}

from user input I get a JSON object 'newData' of the form

{desc:'yyy',status:'complete'}

the way I am updating my mongodb row with this newData is something like

db.tasks.update({_id:newData.id},{$set:{desc:newData.desc,status:newData.status}})

there are only two fields here, so using $set on each pair in newData is OK, but my question is can I update the row, without having to write $set on each pair in newData, just mentioning newData once. (obviously I will keep the pair keys in newData the same as the ones is mongodb row)

4

1 回答 1

1

因为字段名称匹配,你可以直接newData在你的$set喜欢这样使用:

db.tasks.update({_id:newData.id}, {$set: newData})

但是,如果您不验证newData包含哪些字段,这可能会将不需要的数据添加到您的任务文档中。

于 2013-01-03T13:54:52.363 回答