你不能同时使用 ,并 在相同的更新表达式作为嵌套的运营商。
使用更新运算符的正确语法如下:
{
<operator1>: { <field1>: <value1>, ... },
<operator2>: { <field2>: <value2>, ... },
...
}
在那里<operator1>, <operator2>
可以来自任何指定的更新列表运营商的位置。
要将一个新元素添加到数组中,只需一个 运算符即可,例如,您可以使用 update方法将修改后的文档返回为
Employeehierarchy.findByIdAndUpdate(employeeparent._id,
{ "$push": { "childrens": employee._id } },
{ "new": true, "upsert": true },
function (err, managerparent) {
if (err) throw err;
console.log(managerparent);
}
);
使用原始 方法,语法为
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)
位置
由于您要检查修改后的文档,因此建议您使用此 函数,因为该 方法不会提供修改后的文档,而只会提供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);
}
);