[英]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.