Javascript Meteor:将子文档添加到现有记录

Javascript Meteor:将子文档添加到现有记录,javascript,mongodb,meteor,Javascript,Mongodb,Meteor,我有以下计划: dGroup = new SimpleSchema({ title: { type: String, optional: true }, element: { type: String, optional: true } }); MongoDB.attachSchema(new SimpleSchema({ title: { type: String }, slug: { type: String, uniq

我有以下计划:

dGroup = new SimpleSchema({
    title:      { type: String, optional: true },
    element:    { type: String, optional: true }
});

MongoDB.attachSchema(new SimpleSchema({
    title:      { type: String },
    slug:       { type: String, unique: true },
    language:   { type: String, defaultValue: "en" },
    group:      { type: [dGroup], optional: true },
}));
。。。在数据库中,我得到了以下信息:

{ "_id" : "ag9qXWpCYm87kZbEk", "title" : "Test", "slug" : "test", "language" : "en" }
现在我想添加一个dGroup->title:

updates['group.title'] = 'insert this as a new group title with no element';
MongoDB.update({ _id: Id }, { $push: updates }, function(error) { if(error) console.warn(error); });

但这不起作用。因此,我需要一些帮助,以便在meteor中添加子文档,以防它们不存在。

尝试先声明您的对象,然后正确地推送它,如下所示:

var newGroup = {
  title: 'insert this as a new group title with no element'
};
MongoDB.update({ _id: Id }, { $push: {group: newGroup }}, function(error) { if(error) console.warn(error); });

文档说,如果字段不是数组,操作将失败($push)。我认为子元素在技术上不是数组?(title)它和$set一起工作吗?你能解释一下你的代码和我的代码之间的区别吗?基本上你是在做
MongoDB.update({u id:id},{$push:{'group.title':'some string'})
。因此,在您的情况下,Mongo希望
dGroup.title
属性是
字符串的
数组
,但您的模式不是这样说的:它说它只是一个
字符串
。您要做的是告诉Mongo将
对象
(而不是
字符串
)推入
MongoDB.group
,该组可以方便地定义为模式中
对象
数组