Blu Blu - 13 days ago 4
Node.js Question

Mongoose - find() with multiple ids that are the same

If I were to perform this query with mongoose;

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


The query will only return something like:

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


With the array only having one object, obviously because I passed in all the same id's. However, I actually want duplicate objects returned. How can I do this?

rsp rsp
Answer

Mongo itself will only return objects with no duplicates. But you can then build an array of objects with duplicates from that.

For example, if array is the array of objects returned my Mongo - in this case:

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

and ids is your list of IDs that you want with duplicates - in your case:

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

then you can do:

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

Now dupArray should contain the objects with duplicates.

Full example:

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);
  }
});
Comments