2016-03-05 77 views
0

我必須從文檔中的子模板數組中移除項目。MongoDB&Mongoose:如何在使用pull時獲取刪除項目的索引?

SubSchema = new mongoose.Schema({...}) 
MySchema = new mongoose.Schema({someArray: [SubSchema]}) 
(...) 
mydoc.somearray.pull(req.body.submodel_id); 

不過,我需要的是已被刪除,通知所有連接的客戶端的元素的索引。

有沒有一個優雅的解決方案,或者我必須使用_.findIndex或類似的東西? (我想,有更糟糕的表現,因爲它不必要地遍歷數組兩次)

回答

1

不知道一個優雅的解決方案存在這是MongoDB的沒有返回數組元素 的索引更新操作中被拉的方式。一種方法(儘管我認爲這是一個骯髒的黑客攻擊)將獲得更新操作後的原始 陣列,並在更新回調中使用Array.indexOf()獲取刪除的元素索引。

考慮使用findOneAndUpdate()得到更新文檔以下更新操作:

var submodel_id = req.body.submodel_id, 
    query = { "someArray": submodel_id }; 

Model.findOneAndUpdate(
    query, 
    { "$pull": { "someArray": submodel_id } }, 
    { "new": false }, 
    function(err, doc) { 
     var removedIndex = doc.someArray.indexOf(submodel_id); 
     console.log(removedIndex); 
    } 
); 
+0

這仍然搜索文檔兩次,不是嗎? (一次爲拉,一次爲indexOf) 我覺得很奇怪mongoDB&mongoose不支持通過索引刪除(這可以解決我的問題) 無論如何感謝。 –

+0

@ClaasM。不,它不搜索兩次,上述更新操作使用MongoDB的findAndModify()API查詢集合一次,{new:false}選項返回回調中原始未修改的文檔。 – chridam

+0

我在說'IndexOf'。這似乎是沒有必要查詢someArray的submodel_id,然後使用'IndexOf'迭代someArray _again_來找到正確的索引。 –