我有一个Collection,其中包含一组嵌套对象的文档.以下是填充数据库的fixture代码:
if (Parents.find().count() == 0) {
var parentId = Parents.insert({
name: "Parent One"
});
Children.insert({
parent: parentId,
fields: [
{
_id: new Meteor.Collection.ObjectID(),
position: 3,
name: "three"
},
{
_id: new Meteor.Collection.ObjectID(),
position: 1,
name: "one"
},
{
_id: new Meteor.Collection.ObjectID(),
position: 2,
name: "two"
},
]
});
}
Run Code Online (Sandbox Code Playgroud)
您可能会问自己,为什么我只需要根据名称进行更新时就需要ObjectID.这是我正在处理的更复杂的模式的简化示例,并且嵌套对象将动态创建,ObjectID肯定是使这项工作成为必需的.
基本上,我需要一种方法来保存具有唯一ID的嵌套对象,并且能够通过它们的_id更新字段.
这是我的方法,以及我从浏览器控制台进行的调用:
Meteor.methods({
upChild: function( options ) {
console.log(new Meteor.Collection.ObjectID());
Children.update({_id: options._id, "fields._id": options.fieldId }, {$set: {"fields.$.position": options.position}}, function(error){
if(error) {
console.log(error);
} else {
console.log("success");
}
});
}
}); …Run Code Online (Sandbox Code Playgroud)