$对猫鼬模式中定义为对象的字段进行推送操作不会给出错误

问题描述 投票:0回答:1

我有一个猫鼬模型定义为

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
        });

看不懂

  1. 如何在对象字段上进行推送操作而不产生错误?
  2. 为什么使用 findByIdAndUpdate 更新有效,而不是 .save() 操作?
mongodb mongoose mongoose-schema
1个回答
0
投票

对于

save()
,默认情况下会打开验证,但对于像
findByIdAndUpdate
这样的更新方法,默认情况下会关闭验证,如果需要,应该通过传递
runValidators: true
作为选项来打开,如下所示:

  let updatedData = await model.findOneAndUpdate(
    { _id: id },
    {
      $push: {
        fieldA: {
          fieldA1,
          fieldA2,
          fieldA3,
        },
      },
    },
    {
      new: true,
      session: mongoSession,
      runValidators: true,
    },
  );

作为参考,请查看 文档

© www.soinside.com 2019 - 2024. All rights reserved.