[英]Updating a mongodb document with JSON object
I want to update a MongoDB docment (using the Javascript db driver). 我想更新MongoDB文档(使用Javascript数据库驱动程序)。 I would like to pass in a JSON object and have that update the document ... something like:
我想传递一个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)
});
}
});
};
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. 如果“配置文件”文档包含_id,则可以使用collection()。save来更新/替换完整的文档。
http://mongodb.github.io/node-mongodb-native/api-generated/collection.html 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(). 使用save()没什么错,但是如果文档已经存在,则update()也会起作用,并且更新文档不需要包含_id,因为它将由update()保留。 The primary advantage of save() is that it will insert the document if it doesn't already exist (called "upsert").
save()的主要优点是,如果文件不存在,它将插入该文件(称为“ upsert”)。 For example, this mongo shell script:
例如,此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())
produces this output, showing that update() also updates the full document selected by id: 产生此输出,显示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 }
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. 如果您使用像Meteor这样的平台,您将无法选择使用
save()
因为该平台尚未“支持”所有MongoDB命令。 As Bruce stated, I've had success passing in a JSON Object with update()
and had no issues updating a full document. 正如Bruce所说,我已经成功地通过
update()
传递了一个JSON对象,并且更新整个文档没有问题。 I've done the following with Meteor: 我已经完成了Meteor的以下操作:
var myUpdatedData = {item1:"data1",item2:"data2",item3:"data3"};
MyCollection.update({_id: existingID}, myUpdatedData));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.