您不能在与嵌套运算符相同的更新表达式中同时使用 $set 和 $push。
使用update operators 的正确语法如下:
{
<operator1>: { <field1>: <value1>, ... },
<operator2>: { <field2>: <value2>, ... },
...
}
其中<operator1>, <operator2> 可以来自指定here 的任何更新运算符列表。
要向数组中添加新元素,单个 $push 运算符就足够了,例如您可以使用 findByIdAndUpdate 更新方法将修改后的文档返回为
Employeehierarchy.findByIdAndUpdate(employeeparent._id,
{ "$push": { "childrens": employee._id } },
{ "new": true, "upsert": true },
function (err, managerparent) {
if (err) throw err;
console.log(managerparent);
}
);
使用你原来的 update() 方法,语法是
Employeehierarchy.update(
{ "_id": employeeparent._id},
{ "$push": { "childrens": employee._id } },
function (err, raw) {
if (err) return handleError(err);
console.log('The raw response from Mongo was ', raw);
}
);
其中回调函数接收参数(err, raw) where
-
如果发生任何错误,
err 就是错误
-
raw 是 Mongo 的完整回复
由于您要查看修改后的文档,我建议您使用 findByIdAndUpdate 函数,因为 update() 方法不会给您修改后的文档文档,只是 mongo 的完整写入结果。
如果您想更新文档中的字段并同时将元素添加到数组中,那么您可以这样做
Employeehierarchy.findByIdAndUpdate(employeeparent._id,
{
"$set": { "name": "foo" },
"$push": { "childrens": employee._id }
}
{ "new": true, "upsert": true },
function (err, managerparent) {
if (err) throw err;
console.log(managerparent);
}
);
上面会将name字段更新为“foo”并将员工ID添加到childrens数组中。