我在猫鼬中预先删除了许多中间件,并且该中间件的算法会迭代其他模型,因此我想将此算法封装为可用于其他模型的函数。
但是当我通过 next 作为参数来执行此错误时,就会出现该错误:
下一个不是函数
我原来的中间件是:
ShahrestanSchema.pre("deleteMany", function (next) {
console.log('shahrestan-remove-controller-start')
const { OstanModel } = require('./Ostan');
const shahrestan_id_qry = this._conditions._id;
OstanModel.find({ shahrestans: shahrestan_id_qry })
.then(ostans => {
Promise.all(
ostans.map(ostan =>
OstanModel.findByIdAndUpdate(
ostan._id,
{ $pullAll: { shahrestans: shahrestan_id_qry['$in'] } },
{ new: true }
)
))
.then(() => {
console.log('shahrestan-remove-controller-end')
next()
})
.catch(ex => next(new Error(ex)))
});
});
这很好用,但是当我封装如下时:
function deleteManyController(thisOp, next, parentModel, parentKey) {
console.log('shahrestan-remove-controller-start')
const this_id_qry = thisOp._conditions._id;
parentModel.find({ parentKey: this_id_qry })
.then(findeds => {
Promise.all(
findeds.map(finded =>
parentModel.findByIdAndUpdate(
finded._id,
{ $pullAll: { parentKey: this_id_qry['$in'] } },
{ new: true }
)
))
.then(() => {
console.log('shahrestan-remove-controller-end')
next()
})
.catch(ex => next(new Error(ex)))
});
}
并如下更改我的中间件:
ShahrestanSchema.post('deleteMany', function (next) {
const thisOp = this
deleteManyController(thisOp, next, OstanModel, 'shahrestans')
})
此错误的产生:
TypeError:下一个不是函数
您对将中间件封装为功能有任何想法吗?