不能在同一个更新表达式中同时使用100和101作为嵌套运算符.
使用update operators的正确语法如下:
{
<operator1>: { <field1>: <value1>, ... },
<operator2>: { <field2>: <value2>, ... },
...
}
其中<operator1>, <operator2>
可以来自指定为here的任何更新运算符列表.
要向数组中添加新元素,一个100运算符就足够了,例如,您可以使用101 update方法将修改后的文档作为
Employeehierarchy.findByIdAndUpdate(employeeparent._id,
{ "$push": { "childrens": employee._id } },
{ "new": true, "upsert": true },
function (err, managerparent) {
if (err) throw err;
console.log(managerparent);
}
);
使用最初的100方法,语法是
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)
,其中
- 如果出现任何错误,则为
err
raw
是Mongo的完整回复
既然你想判断修改过的文档,我建议你使用100函数,因为101方法不会给你修改过的文档,只是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
数组中.