使用JSON对象更新mongodb文档

时间:2014-02-23 23:35:20

标签: javascript node.js mongodb

我想更新MongoDB文档(使用Javascript db驱动程序)。我想传入一个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)
        });
    }
  });
};

我希望这是一个通用函数,所以如果文档结构发生变化,我就不必重写了。目前,我只能使用

来实现这一目标
{"$set": {x:profile.x, y:profile.y}}

在更新中,是否有人拥有通用解决方案,以便我可以传入任何配置文件:

profile = { .... }

3 个答案:

答案 0 :(得分:2)

如果“profile”文档包含_id,则可以使用collection()。save来更新/替换完整文档。

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

答案 1 :(得分:0)

使用save()没有任何问题,但如果文档已经存在,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()还更新由id:

选择的完整文档
{ "_id" : 0, "x" : 1, "y" : 2 }
{ "_id" : 0, "x" : 3, "y" : 4, "z" : 5 }
{ "_id" : 0, "x" : 6, "y" : 7, "z" : 8, "w" : 9 }

答案 2 :(得分:0)

如果您使用像Meteor这样的平台,您将无法使用save(),因为平台尚未“支持”所有MongoDB命令。正如Bruce所说,我已经成功传递了update()的JSON对象,并且在更新完整文档时没有任何问题。 我用Meteor完成了以下工作:

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