2016-11-21 17 views
0

如果我要用貓鼬執行此查詢;貓鼬 - 找到()與多個ID是相同的

Schema.find({ 
    _id: { 
     $in: ['abcd1234', 'abcd1234', 'abcd1234'] 
    } 
}); 

查詢只會返回類似:

[{ 
    'property1': 'key1', 
    'property2': 'key2' 
}] 

與陣列只有一個對象,顯然是因爲我在所有相同ID的通過。但是,我實際上希望返回重複的對象。我怎樣才能做到這一點?

回答

1

Mongo本身只會返回沒有重複的對象。但是你可以用這些重複的東西來構建一個對象數組。

例如,如果array是對象的數組回到我的蒙戈 - 在這種情況下:

var array = [{ 
    _id: 'abcd1234', 
    property1: 'key1', 
    property2: 'key2' 
}]; 

ids是你要與重複的ID清單 - 在你的情況:

var ids = ['abcd1234', 'abcd1234', 'abcd1234']; 

那麼你可以做:

var objects = {}; 
array.forEach(o => objects[o._id] = o); 
var dupArray = ids.map(id => objects[id]); 

現在dupArray應該包含具有重複項的對象。

完整的示例:

var ids = ['abcd1234', 'abcd1234', 'abcd1234']; 
Schema.find({_id: {$in: ids}}, function (err, array) { 
    if (err) { 
    // handle error 
    } else { 
    var objects = {}; 
    array.forEach(o => objects[o._id] = o); 
    var dupArray = ids.map(id => objects[id]); 
    // here you have objects with duplicates in dupArray: 
    console.log(dupArray); 
    } 
});