【问题标题】:Is there a pre/post hook that fires both on save and update?是否有在保存和更新时触发的前/后挂钩?
【发布时间】:2019-11-13 22:43:36
【问题描述】:

我有例如。

schema.pre('save', (next) => {
  console.log('save fired');
  next();
});

我认为“保存”会触发所有 schema.update()schema.create() 事件,因为这两个事件在技术上都是“保存”的东西。

例如,修改架构中的值 unique: true 的操作,需要检查新值是否不会引发 DuplicateKey (11000) 错误并引发自己的错误。

有没有比以下更清洁的方法:

const createUpdateCommon = (next) => {/*check if thrown DuplicateKey error*/}

schema.pre('save', createUpdateCommon);
schema.pre('findOneAndUpdate', createUpdateCommon);

还有没有任何 pre hook 可以处理“任何更新”,而不必指定 findOne、findMany 等?

【问题讨论】:

    标签: mongodb mongoose mongoose-schema


    【解决方案1】:

    还有没有任何 pre hook 可以处理“任何更新”,而不必指定 findOne、findMany 等?

    没有。您需要手动提供每一个。

    例如,修改模式中唯一值的操作:true,需要检查新值是否不会抛出 DuplicateKey (11000) 错误并抛出自己的错误。

    https://stackoverflow.com/a/38946126/10706046 - 你需要为每个操作创建一个钩子。

    我假设“保存”会在所有 schema.update() 和 schema.create() 事件上触发,因为这两者在技术上都是“保存”的东西。

    没有。这是 MongoDB 中的两个独立操作。您需要为createfindOneAndUpdate 创建一个挂钩。

    顺便说一句,我的问题是我正在为createUpdateCommon(incomingData) 中的创建和更新实施验证。

    我正在检查传入的数据(在创建或更新时)是否不是例如引用一个不存在的 countryId。

    所以在createUpdateCommon 我有类似city.findOne(incomingData.city) 的东西。

    不要为此使用钩子。改用架构验证器
    像这样:

    const userSchema = new Schema({
      name: String,
      city: {
        type: String, //probably use ObjectID instead
        validator: (value) => !!cityModel.findOne(value.city) //returns true if finds a city
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-13
      • 2020-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-07
      • 2020-02-12
      相关资源
      最近更新 更多