Javascript 在MongoDB中插入嵌套文档
我试图在类似于的结构中向上插入嵌套文档(活动)Javascript 在MongoDB中插入嵌套文档,javascript,mongodb,meteor,Javascript,Mongodb,Meteor,我试图在类似于的结构中向上插入嵌套文档(活动) { "_id" : "123", "modules" : { "x" : { }, "y" : { "activities" : { "preview": { "createdAt": "2014-10-13 15:21:22.113", "data": {} } } }, "z" : { "a
{
"_id" : "123",
"modules" : {
"x" : {
},
"y" : {
"activities" : {
"preview": {
"createdAt": "2014-10-13 15:21:22.113",
"data": {}
}
}
},
"z" : {
"activities" : {
"render": {
"createdAt": "2014-10-15 04:22:25.171",
"data": {}
},
"render": {
"createdAt": "2014-10-14 02:42:24.132",
"data": {}
}
}
}
}
}
然后我试试看
selector = { "_id": id, "modules": module, "activities" }
activity = { "preview": { "data": data }}
Meteor.users.upsert(selector, { $set: activity, $setOnInsert: { "createdAt: new Date()" }})
产生
MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: meteor.users.$_id_ dup key: { : "123" }
\u id
是唯一的索引键。在每个用户的\u id
“级别”和每个模块的活动
“级别”上都有额外的字段/文档,但没有与upsert相关的字段/文档。每个模块都是唯一的。插入第一条记录之前,活动文档不存在
有了这些,我希望有人能了解我要完成的工作的要点,并能帮助我朝着正确的方向前进。Upsert用于插入或更新(如果存在)新文档。它不适用于子文档 您只需更新您的文档:
selector = { "_id": id, "modules": module, preview : null }
activity = { "preview": { "data": data , "createdAt" : new Date() }}
Meteor.users.update(selector, { $set: 'activity' : activity }})
我不太明白。如果子文档存在,我想将其插入(但不更新其createdAt)。答案已更新。不能对子文档使用upsert。您应该检查预览是否不存在,然后使用update命令添加新字段名预览;)