Mongoose模型post 'remove'中间件触发类型错误问题排查
问题解决方案
错误1:重载匹配错误
该错误源于当前Mongoose版本的类型定义中,文档级post中间件不再支持'remove'事件(doc.remove()方法已被弃用),官方推荐使用'deleteOne'事件替代,对应现在的doc.deleteOne()文档删除方法。
错误2:next()函数调用错误
当使用async/await编写Mongoose中间件时,不需要next参数——异步函数的返回结果或抛出的异常会被Mongoose自动处理,无需手动调用next()。
修正后的代码
const eventSchema = new Schema<EventInterface>({ userId: { type: String, required: true }, studio: { type: Schema.Types.ObjectId, ref: 'Studio' }, shifts: [{ type: Schema.Types.ObjectId, ref: 'Shift' }], date: { type: Date, required: true }, class: { type: Schema.Types.ObjectId, ref: 'Class', required: true }, isActive: { type: Boolean, default: true } }, { timestamps: true, versionKey: false }); // 替换为deleteOne事件的post中间件,移除next参数 eventSchema.post<EventInterface>('deleteOne', { document: true }, async function () { const event = this; const Shift = model('Shift'); // 删除关联的所有Shift文档 await Shift.deleteMany({ _id: { $in: event.shifts } }); });
补充说明
- 若需兼容旧代码保留
remove事件,可临时用// @ts-ignore忽略类型错误,但不推荐——remove方法已被官方标记为弃用,后续版本可能移除支持。 - 异常处理:如果
deleteMany执行出错,async函数会自动将异常传递给Mongoose,由框架处理后续错误流程;若需自定义错误逻辑,可添加try/catch块并抛出自定义异常。
内容的提问来源于stack exchange,提问作者sonEtLumiere
相关产品推荐
相关产品推荐

