簡體   English   中英

MongoDB和Mongoose:使用pull時,如何獲取已刪除項目的索引?

[英]MongoDB & Mongoose: How do I get the index of the removed item when using pull?

我必須從文檔的子計划數組中刪除一項。

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

但是,我需要已刪除的元素的索引才能通知所有連接的客戶端。

是否有一個優雅的解決方案,還是我必須使用_.findIndex或類似的東西? (我想這會導致性能下降,因為它不必要地對數組進行兩次迭代)

由於MongoDB無法返回在更新操作中提取的數組元素的索引,因此無法確定是否存在完善的解決方案。 一種方法(盡管我認為這是一種骯臟的技巧)是在更新操作之后獲取原始數組,並在update回調中使用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);
    }
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM