有没有办法在 Mongoose 中删除父项的所有子项,类似于使用 MySQL 的外键?
例如,在 MySQL 中,我会分配一个外键并将其设置为级联删除。因此,如果我要删除一个客户端,所有应用程序和相关用户也将被删除。
从顶层看:
- 删除客户
- 删除抽奖事件
- 删除提交内容
抽奖和提交都有一个 client_id 字段。提交有一个用于 sweepstakes_id 和 client_id 的字段。
现在,我正在使用以下代码,我觉得必须有更好的方法。
Client.findById(req.params.client_id, function(err, client) {
if (err)
return next(new restify.InternalError(err));
else if (!client)
return next(new restify.ResourceNotFoundError('The resource you requested could not be found.'));
// find and remove all associated sweepstakes
Sweepstakes.find({client_id: client._id}).remove();
// find and remove all submissions
Submission.find({client_id: client._id}).remove();
client.remove();
res.send({id: req.params.client_id});
});
最佳答案
这是 Mongoose 的'remove'
的主要用例之一 middleware .
clientSchema.pre('remove', function(next) {
// 'this' is the client being removed. Provide callbacks here if you want
// to be notified of the calls' result.
Sweepstakes.remove({client_id: this._id}).exec();
Submission.remove({client_id: this._id}).exec();
next();
});
这样,当您调用 client.remove()
时,会自动调用此中间件来清理依赖项。
关于mongodb - Mongoose 中的级联样式删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44573741/