mongodb - Mongoose 中的级联样式删除

标签 mongodb mongoose

有没有办法在 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});

});

最佳答案

这是 Mongoose 的'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() 时,会自动调用此中间件来清理依赖项。

关于mongodb - Mongoose 中的级联样式删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44573741/

相关文章:

javascript - Mongoose 聚合成一个嵌套的 doc 获取计数并将新值附加到查询结果

javascript - 根据嵌入文档的数量对记录进行排序

node.js - Mongoose 更新嵌入文档

node.js - 使用 Mongoose 查找byid 并更新同级

mongodb - 使用 $elemMatch 更新 mongodb 嵌入式文档

javascript - MEAN.JS 无法连接 MongoDB

mongodb - 有什么可以限制mongodb cpu的使用吗?

ruby-on-rails-3 - 具有多个字段的 Mongoid order_by 导致意外

javascript - 在 Mongoose 中,找不到模块 '\node_modules\ipaddr.js\lib\ipaddr.js' 。请验证 package.json 是否具有有效的 "main"条目

node.js - 使用 mongoose 将对象数组推送到 mongodb 中