【发布时间】:2012-12-30 04:30:39
【问题描述】:
有没有办法在 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});
});
【问题讨论】: