有没有办法在 Mongoose 中删除父级的所有子级,类似于使用 MySQL 的外键?
例如,在 MySQL 中,我会分配一个外键并将其设置为删除时级联。因此,如果我要删除客户端,所有应用程序和关联用户也会被删除。
从顶层:
抽奖和提交都有一个 client_id 字段。 Submissions 有一个用于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()
时,会自动调用此中间件来清理依赖关系。
https://stackoverflow.com/questions/14348516/
相关文章:
node.js - 如何使用 Mongoose findOne
ruby-on-rails - 批量查找 mongoDB 记录(使用 mongoid ruby
mongodb - 在 node.js 和 mongodb 中创建注册和登录表单
mongodb - 如何使用 Scala 将 1 亿条记录加载到 MongoDB 中进行性能测试?
node.js - Node.js/Mongoose 上的 "VersionError: No ma
ruby-on-rails - mongoid 中 embeds_many 和 has_many 的
mongodb - 在 MongoDB 中使用 UUID 而不是 ObjectID