简体   繁体   中英

Updating a mongodb document with JSON object

I want to update a MongoDB docment (using the Javascript db driver). I would like to pass in a JSON object and have that update the document ... something like:

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)
        });
    }
  });
};

I want this to be a generic function, so that if the document structure changes I don`t have to re-write. At the moment I can only get this working by using

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

in the update, does anyone have a generic solutions so that I can pass in any profile:

profile = { .... }

If "profile" document contains the _id, you can use the collection().save which updates/replaces a full document.

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

There's nothing wrong with using save(), but update() will work also if the document already exists, and the update document does not need to contain the _id as it will be preserved by the update(). The primary advantage of save() is that it will insert the document if it doesn't already exist (called "upsert"). For example, this mongo shell script:

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())

produces this output, showing that update() also updates the full document selected by 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 }

If you use a platform like Meteor you will not have the option to use save() as the platform does not "yet" support the full range of MongoDB commands. As Bruce stated, I've had success passing in a JSON Object with update() and had no issues updating a full document. I've done the following with Meteor:

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

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