【发布时间】: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