我想更新一个数组值,但我不确定执行此操作的正确方法,因此我尝试了以下方法,但对我不起作用。
我的模特, 我的模型中的 Children 字段
childrens: {
type: Array,
default: ''
}
我的询问,
Employeehierarchy.update({ _id: employeeparent._id} ,{ $set: {"$push": { "childrens": employee._id }} })
.exec(function (err, managerparent) {});
任何人都可以帮助我吗?谢谢。
$set
和 $push
作为嵌套运算符。
使用更新运算符的正确语法如下:
{
<operator1>: { <field1>: <value1>, ... },
<operator2>: { <field2>: <value2>, ... },
...
}
其中
<operator1>, <operator2>
可以来自于此处指定的任何更新操作符列表。
$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)
其中
err
如有发生则为错误raw
是Mongo的完整回复findByIdAndUpdate
函数,因为 update()
方法不会给你修改后的文档,只是完整的写入结果蒙戈。
如果您想更新文档中的字段并同时向数组添加元素,那么您可以这样做
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
数组中。
可以关注这个
如果
childrens
包含字符串值,那么模型可以是这样的:
childrens: [{
type : String
}]
如果
childrens
包含另一个集合 _id
的 ObjectId 值并且想要填充,那么模型可以是这样的:
childrens: [{
type : mongoose.Schema.Types.ObjectId,
ref: 'refModelName'
}]
无需使用
$set
只需使用 $push
在 childrens
数组中插入值即可。所以查询可以是这样的:
Employeehierarchy.update(
{ _id: employeeparent._id},
{"$push": { "childrens": employee._id } }
).exec(function (err, managerparent) {
//
});
我想这会有帮助
Employeehierarchy.findOneAndUpdate(
{ _id:employeeparent._id },
{ $set: { "childrens": employee._id }}
)
在 mongoose v8 中,语法更清晰、更易读:
const body = request.body;
await JourneyModel.updateOne({
"days._id": body._id
},{
$set: {
'days.$.driverName': body.driverName,
'days.$.driverPhone': body.driverPhone,
'days.$.driverNeeded': false,
'days.$.driverInfoUpdatedBy': new mongo.ObjectId(user._id).toString(),
'days.$.lastModifiedAt': new Date().toISOString(),
}
})