我正在使用nodejs和mongoose为训练营和课程制作API,两者之间的关系是训练营可能有很多课程。
现在我正在尝试级联删除,因此当我删除训练营时,所有相关课程也应该被删除。
在我的模型训练营中:
// Cascade delete courses when a bootcamp is deleted
BootcampSchema.pre('remove', async function(next) {
console.log(`Courses being removed from bootcamp ${this._id}`);
await this.model('Course').deleteMany({ bootcamp: this._id });
next();
});
// Reverse populate with virtuals
BootcampSchema.virtual('courses', {
ref: 'Course',
localField: '_id',
foreignField: 'bootcamp',
justOne: false
});
bootcamps.js(控制器):
// @desc Delete a Bootcamp
// @route DELETE /api/v1/bootcamps/:id
// @access Private
exports.deleteBootcamp = asyncHandler(async (req, res, next) => {
const bootcamp = await Bootcamp.findById(req.params.id);
if(!bootcamp) {
return next(new ErrorResponse(`Bootcamp not found with id of ${req.params.id}`, 404));
}
bootcamp.remove();
res.status(200).json({ success: true, data: {} });
})
所以我在邮递员中发送请求,并收到以下错误:
bootcamp.remove is not a function
知道为什么会发生这种情况吗?还有其他方法可以解决这个问题吗?
我真的不知道
remove()
是否已被弃用,正如您在评论中提到的那样,您的代码看起来不错。如果您确实可以使用
bootcamp
获得 await Bootcamp.findById(req.params.id)
,那么为您的类 Bootcamp
创建的模式就已正确构建。另一种选择是使用
deleteOne()
代替。
await Bootcamp.deleteOne({id: req.params.id}); // or {_id: req.params.id} depending on the id field name in your schema
您还必须为此更新中间件:
BootcampSchema.pre('deleteOne', async function(next) { // replace 'remove' with 'deleteOne'
// your logic
});
将
remove
替换为 deleteOne
中间件
// Cascade delete courses when a bootcamp is deleted
BootcampSchema.pre('deleteOne', { document: true, query: false }, async function(next){
console.log(`Courses being removed from bootcamp ${this._id}`);
await this.model('Course').deleteMany({bootcamp: this._id});
next();
});
exports.deleteBootcamp = asyncHandler(async (req, res, next) => {
const bootcamp = await Bootcamp.findById(req.params.id);
if (!bootcamp) {
return next(
new ErrorResponse(`Bootcamp not found with id of ${req.params.id}`, 404)
);
}
await bootcamp.deleteOne();
res.status(200).json({ success: true, data: {} });
});
我遇到了同样的问题,无法让
deleteOne
工作。 remove
确实有效,只是缺少等待。
await bootcamp.remove();