猫鼬中的级联样式删除 [英] Cascade style delete in Mongoose

查看:68
本文介绍了猫鼬中的级联样式删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以删除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.

从顶层开始:

  1. 删除客户端
  2. 删除抽奖活动
  3. 删除提交的内容

抽奖和提交都有一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆