2017-04-25 97 views
1

我有一個users集合和每個user有多個聯繫人。當user刪除其帳戶時,我希望該用戶的ID將從該用戶所連接的所有用戶的聯繫人數組中刪除。我試過這Model.Update查詢,但它不起作用。這是我到目前爲止的代碼:Node.js MongoDB - 如何使用Mongoose更新多個文檔?

   User.update({'userId':{ $in: userIds }, 
         $pullAll: {'contacts': [myId] },'multi': true 
        },function(err, count) { 
         if(err){ 
          console.log(err); 
         }else{ 
          console.log(count); 
         } 
        }); 
+0

我認爲'userIds'是ID的對需要被移除並隨後從其他用戶的'contacts'陣列中刪除用戶的陣列,對嗎?你還可以更新你的問題來顯示User模型的模式定義嗎? – chridam

+0

@chridam是的,正確的。 – Nikolaj

回答

3

的更新文檔和multi應該作爲單獨的參數傳遞:

User.update({ 
    userId : { $in : userIds }  // conditions 
}, { 
    $pullAll : { contacts : [myId] } // document 
}, { 
    multi : true      // options 
}, function(err, count) { 
    if (err) { 
    console.log(err); 
    } else { 
    console.log(count); 
    } 
}); 

文檔here

+0

謝謝,它的工作原理。 – Nikolaj

0

可以更新多個文檔,多個條件

Model.update({ 
    _id : { $in : ids}  // conditions 
}, { 
    $set: {deletion_indicator: constants.N} // document 
}, { 
    multi : true      // options 
}, function(err, result) { 
    if (err) { 
     console.log(err); 
    } else { 
     console.log(result); 
    } 
}); 
相關問題