添加到子文档数组

Add to array of sub documents

我想知道 Mongoose 中是否有一种方法可以通过添加到现有 child 集合来同时对所有文档中的 child 集合进行批量更新。

我有以下文档结构:

{
 name:'',
 type:'',
 children:[]
}

//the documents have existing children.
myDocumentModel.update({},{children:newChildren}, { multi: true }).exec();

上面的代码不是我想要的。它确实更新了所有文档,但它覆盖了 children 而不是向现有文档添加新的 children。 有没有我可以给 Mongoose 的线索,让更新成为附加内容而不是替换原来的 children?

您可以使用 $push operator with the $each 修饰符将元素数组添加到数组字段:

myDocumentModel.update({},
    { $push: { children: { $each: newChildren } } },
    { multi: true }
).exec();