用JSON对象更新MongoDB文档

我想更新一个MongoDB文档(使用Javascript数据库驱动程序)。 我想通过一个JSON对象,并有更新文件…像这样:

Provider.prototype.updateProfile = function(username, profile, callback) { this.getCollection(function(error, profile_collection) { if( error ) callback( error ); else { profile_collection.update( {username: username}, {profile}, function(error, profile){ if( error ) callback(error); else callback(null, profile) }); } }); }; 

我希望这是一个通用的function,所以如果文档结构的变化,我不必重新写。 目前我只能使用这个工作

 {"$set": {x:profile.x, y:profile.y}} 

在更新中,有没有人有一个通用的解决scheme,以便我可以通过任何configuration文件:

 profile = { .... } 

如果“profile”文件包含_id,则可以使用collection()。保存哪些更新/replace完整的文档。

http://mongodb.github.io/node-mongodb-native/api-generated/collection.html

使用save()没有什么问题,但是如果文档已经存在,update()也可以工作,并且update文档不需要包含_id,因为它将被update()保留。 save()的主要优点在于,如果文档不存在(称为“upsert”),它将插入文档。 例如,这个mongo shell脚本:

 db.collection.insert({_id:0, x:1, y:2}) printjson(db.collection.findOne()) db.collection.update({_id:0}, {x:3, y:4, z:5}) printjson(db.collection.findOne()) db.collection.save({_id:0, x:6, y:7, z:8, w:9}) printjson(db.collection.findOne()) 

产生这个输出,显示update()也更新由idselect的完整文档:

 { "_id" : 0, "x" : 1, "y" : 2 } { "_id" : 0, "x" : 3, "y" : 4, "z" : 5 } { "_id" : 0, "x" : 6, "y" : 7, "z" : 8, "w" : 9 } 

如果你使用像Meteor这样的平台,你将不能使用save()因为平台不支持所有的MongoDB命令。 正如Bruce所说的,我已经成功地通过update()传递了一个JSON对象,并且没有更新完整文档的问题。 我用Meteor完成了以下工作:

 var myUpdatedData = {item1:"data1",item2:"data2",item3:"data3"}; MyCollection.update({_id: existingID}, myUpdatedData));