我收集的文档的结构是这样的。
{
"_id" : ObjectId("54e74de2950fd3a4e5f0a37a"),
"userName": "Any_user",
"ratings": {
"rating1" : [ ],
"big_rating" : [ ]
}
}
Run Code Online (Sandbox Code Playgroud)
在 MongoDB 客户端 (mongo.exe) 中,我需要的添加看起来像这样
db.userContent.update({userName: "NXTaar"}, {$set: {"ratings.variable_name": []}})
Run Code Online (Sandbox Code Playgroud)
我需要 MongoDB node.js 驱动程序的函数是的,我知道“属性名称作为字符串”的事情,我可以将变量传递给属性名称。这是我试图做的:
var rating = {};
var title = 'some_string';
ratings[title] = [];
usercontent.update({userName: "some_user"}, {$set: ratings}, function (err, doc) {...})
Run Code Online (Sandbox Code Playgroud)
这一行向文档添加了一个名为 property 的新对象
usercontent.update({userName: "some_user"}, {$set: {ratings: ratings}}, function (err, doc) {...})
Run Code Online (Sandbox Code Playgroud)
而这个正是我所需要的,但每次运行时,它都会用一个新的属性重写当前属性(是的,我知道,这是因为 $set 参数用你传递给它的东西改变了选定的对象)
我需要一个函数,它向对象添加一个属性,并通过变量给定名称