Mongoose 中的级联样式删除 [英] 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 的字段.提交有一个用于sweettakes_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.
这篇关于Mongoose 中的级联样式删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!