在猫鼬中删除级联样式

在猫鼬中删除级联样式

有没有办法删除Mongoose中父级的所有子级,类似于使用MySQL的外键?

例如,在MySQL中,我将分配一个外键并将其设置为在删除时级联。因此,如果我要删除客户端,则也会删除所有应用程序和关联用户。

从顶层:

  1. 删除客户端

  2. 删除抽奖活动

  3. 删除提交

抽奖和提交都有一个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});});


UYOU
浏览 863回答 3
3回答

杨魅力

这是Mongoose 'remove' 中间件的主要用例之一。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()此中间件时,将自动调用以清除依赖项。

慕神8447489

如果您的引用以其他方式存储,比如说,client有一个数组submission_ids,那么以与接受的答案类似的方式,您可以定义以下内容submissionSchema:submissionSchema.pre('remove', function(next) {     Client.update(         { submission_ids : this._id},          { $pull: { submission_ids: this._id } },         { multi: true })  //if reference exists in multiple documents      .exec();     next();});这将从客户端的 引用数组中删除提交的 id 。submission.remove()

慕尼黑5688855

这是我发现的另一种方式submissionSchema.pre('remove', function(next) {     this.model('Client').remove({ submission_ids: this._id }, next);     next();});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

MongoDB