我有一个猫鼬模型定义为
const definedSchema = mongoose.Schema({
fieldA1: { type: String },
fieldA2: { type: String },
fieldA3: { type: Date },
});
const schema = mongoose.Schema(
{
fieldA: { type: definedSchema },
fieldB: { type: definedSchema },
fieldC: { type: definedSchema },
}
);
const model = mongoose.model('model', schema);
现在我正在使用以下代码对模型执行更新操作 -
let updatedData = await model.findOneAndUpdate(
{ _id: id },
{
$push: {
fieldA: {
fieldA1,
fieldA2,
fieldA3,
},
},
},
{
new: true,
session: mongoSession,
},
);
猫鼬在对象字段上执行推送时不会生成错误。 在 MongoDB 指南针中,fieldA 也显示为存储为具有多个对象的数组。
但是当我从集合中获取数据并尝试使用下面的代码更新 fieldB 和 fieldC 时 -
const data = await model.findOne({
filter,
});
obj.fieldB=x;
obj.fieldC=y;
await obj.save();
我遇到错误
ValidationError: model validation failed: fieldA: Tried to set nested object field `fieldA` to array `[object Object]` and strict mode is set to throw .
但是当我使用 finByIdAndUpdate 更新 fieldB 和 fieldC 时,它工作正常
await model.findByIdAndUpdate(id,
{
fieldA,
fieldB
});
看不懂
对于
save()
,默认情况下会打开验证,但对于像 findByIdAndUpdate
这样的更新方法,默认情况下会关闭验证,如果需要,应该通过传递 runValidators: true
作为选项来打开,如下所示:
let updatedData = await model.findOneAndUpdate(
{ _id: id },
{
$push: {
fieldA: {
fieldA1,
fieldA2,
fieldA3,
},
},
},
{
new: true,
session: mongoSession,
runValidators: true,
},
);
作为参考,请查看 文档