在貓鼬中刪除級(jí)聯(lián)樣式有沒有辦法刪除Mongoose中父級(jí)的所有子級(jí),類似于使用MySQL的外鍵?例如,在MySQL中,我將分配一個(gè)外鍵并將其設(shè)置為在刪除時(shí)級(jí)聯(lián)。因此,如果我要?jiǎng)h除客戶端,則也會(huì)刪除所有應(yīng)用程序和關(guān)聯(lián)用戶。從頂層:刪除客戶端刪除抽獎(jiǎng)活動(dòng)刪除提交抽獎(jiǎng)和提交都有一個(gè)client_id字段。提交的字段包含sweepstakes_id和client_id?,F(xiàn)在,我正在使用以下代碼,我覺得必須有更好的方法。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貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超6個(gè)贊
這是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();});這樣,當(dāng)您調(diào)用client.remove()此中間件時(shí),將自動(dòng)調(diào)用以清除依賴項(xiàng)。
慕神8447489
TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超1個(gè)贊
如果您的引用以其他方式存儲(chǔ),比如說,client有一個(gè)數(shù)組submission_ids,那么以與接受的答案類似的方式,您可以定義以下內(nèi)容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();});這將從客戶端的 引用數(shù)組中刪除提交的 id 。submission.remove()
慕尼黑5688855
TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超2個(gè)贊
這是我發(fā)現(xiàn)的另一種方式
submissionSchema.pre('remove', function(next) {
this.model('Client').remove({ submission_ids: this._id }, next);
next();});- 3 回答
- 0 關(guān)注
- 1040 瀏覽
添加回答
舉報(bào)
0/150
提交
取消
