子文档验证引发不会阻止更新

时间:2019-09-27 02:13:03

标签: mongoose

我有一个带有预验证钩子的子文档。当我创建一个新文档时,该子文档验证失败将适当地阻止该文档的创建。

但是,在更新时,子文档验证将运行并引发错误,但不会阻止文档的更新。无效的子文档数据已保存到数据库。

这是我的架构(为简便起见,已简化):

const contactSchema = new mongoose.Schema(
  {
    firstName: String,
    lastName: String,
    addresses: [addressSchema],
  }
);

const addressSchema = new mongoose.Schema(
  {
    address: String,
    city: String,
    regionId: String,
    postalCode: String,
    countryId: String,
  }
);

// Note: my actual validate hook does a lot more work to validate the full address.
// This is just simplified for demo purposes.
addressSchema.pre(`validate`, function(this) {
  if (!isValidCountryId(this.countryId)) {
    console.log(`THROW`);
    throw new Error(`countryIdIsInvalid`);
  }
});

当我在下面运行此更新时,THROW将从console.log打印出来。但是,联系人文档仍保存有无效的countryId

const update = {
  addresses: [
    {
      address: `12345`,
      city: `Somewhere`,
      regionId: `CA`,
      postalCode: `90000`,
      countryId: ``,
    }
  ]
};

ContactModel.findByIdAndUpdate(
  contactId,
  update,
  { runValidators: true }
);

我想念什么?还是不打算这样做?

0 个答案:

没有答案