在貓鼬中刪除級聯樣式有沒有辦法刪除Mongoose中父級的所有子級,類似于使用MySQL的外鍵?例如,在MySQL中,我將分配一個外鍵并將其設置為在刪除時級聯。因此,如果我要刪除客戶端,則也會刪除所有應用程序和關聯用戶。從頂層:刪除客戶端刪除抽獎活動刪除提交抽獎和提交都有一個client_id字段。提交的字段包含sweepstakes_id和client_id?,F在,我正在使用以下代碼,我覺得必須有更好的方法。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條經驗 獲得超6個贊
這是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
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()

慕尼黑5688855
TA貢獻1848條經驗 獲得超2個贊
這是我發現的另一種方式
submissionSchema.pre('remove', function(next) { this.model('Client').remove({ submission_ids: this._id }, next); next();});
- 3 回答
- 0 關注
- 1005 瀏覽
添加回答
舉報
0/150
提交
取消