亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在貓鼬中刪除級聯樣式

在貓鼬中刪除級聯樣式

UYOU 2019-08-19 10:50:30
在貓鼬中刪除級聯樣式有沒有辦法刪除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()此中間件時,將自動調用以清除依賴項。


查看完整回答
反對 回復 2019-08-19
?
慕神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()


查看完整回答
反對 回復 2019-08-19
?
慕尼黑5688855

TA貢獻1848條經驗 獲得超2個贊

這是我發現的另一種方式

submissionSchema.pre('remove', function(next) {
    this.model('Client').remove({ submission_ids: this._id }, next);
    next();});


查看完整回答
反對 回復 2019-08-19
  • 3 回答
  • 0 關注
  • 1005 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號