[英]Updating a mongodb document with JSON object
我想更新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)
});
}
});
};
我希望这是一个通用函数,因此,如果文档结构发生更改,则不必重新编写。 目前,我只能通过使用
{"$set": {x:profile.x, y:profile.y}}
在更新中,是否有人有通用的解决方案,以便我可以传递任何个人资料:
profile = { .... }
如果“配置文件”文档包含_id,则可以使用collection()。save来更新/替换完整的文档。
http://mongodb.github.io/node-mongodb-native/api-generated/collection.html
使用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 }
如果您使用像Meteor这样的平台,您将无法选择使用save()
因为该平台尚未“支持”所有MongoDB命令。 正如Bruce所说,我已经成功地通过update()
传递了一个JSON对象,并且更新整个文档没有问题。 我已经完成了Meteor的以下操作:
var myUpdatedData = {item1:"data1",item2:"data2",item3:"data3"};
MyCollection.update({_id: existingID}, myUpdatedData));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.