为了账号安全,请及时绑定邮箱和手机立即绑定

在猫鼬中删除级联样式

在猫鼬中删除级联样式

UYOU 2019-08-19 10:50:30
在猫鼬中删除级联样式有没有办法删除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});});
查看完整描述

3 回答

?
杨魅力

TA贡献1811条经验 获得超5个赞

这是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()此中间件时,将自动调用以清除依赖项。


查看完整回答
反对 回复 2019-08-19
?
慕神8447489

TA贡献1780条经验 获得超1个赞

如果您的引用以其他方式存储,比如说,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()


查看完整回答
反对 回复 2019-08-19
?
慕尼黑5688855

TA贡献1848条经验 获得超2个赞

这是我发现的另一种方式

submissionSchema.pre('remove', function(next) {
    this.model('Client').remove({ submission_ids: this._id }, next);
    next();});


查看完整回答
反对 回复 2019-08-19
  • 3 回答
  • 0 关注
  • 853 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信