猫鼬中的级联样式删除 [英] Cascade style delete in Mongoose
问题描述
有没有一种方法可以删除Mongoose中父母的所有孩子,就像使用MySQL的外键一样?
Is there a way to delete all children of an parent in Mongoose, similar to using MySQLs foreign keys?
例如,在MySQL中,我将分配一个外键并将其设置为在删除时级联.因此,如果我要删除客户端,则所有应用程序和关联的用户也将被删除.
For example, in MySQL I'd assign a foreign key and set it to cascade on delete. Thus, if I were to delete a client, all applications and associated users would be removed as well.
从顶层开始:
- 删除客户端
- 删除抽奖活动
- 删除提交的内容
抽奖和提交都有一个client_id字段.提交的字段同时包含swrapstakes_id和client_id.
Sweepstakes and submissions both have a field for client_id. Submissions has a field for both sweepstakes_id, and client_id.
现在,我正在使用以下代码,我觉得必须有更好的方法.
Right now, I'm using the following code and I feel that there has to be a better way.
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'
中间件.
This is one of the primary use cases of Mongoose's '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()
时,将自动调用此中间件以清理依赖项.
This way, when you call client.remove()
this middleware is automatically invoked to clean up dependencies.
这篇关于猫鼬中的级联样式删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!