Reputation: 540
I have an array which contains Id of a mongodb collection
array = [ '573163a52abda310151e5791',
'57358e5dbd2f8b960aecfa8c',
'573163da2abda310151e5792' ]
like this, in my nodejs code I want to find the documents of all these Ids. the package I'm using is mongoskin.
according to the docs this is the correct way to find the result, which is giving me what I want. But here instead of direct values I want to use the array, but unable to find out how to do that
db.coll.find({
_id: {
$in: [mongoskin.helper.toObjectID("573163da2abda310151e5792"),
mongoskin.helper.toObjectID("57358e5dbd2f8b960aecfa8c"),
mongoskin.helper.toObjectID("573163a52abda310151e5791")
]
}
}).toArray(function(err, docs) {
console.log(docs);
res.send(docs)
});
Upvotes: 4
Views: 3097
Reputation: 910
I think this is useful to you
ObjectID = require('mongoskin').ObjectID;
var array1 = ["5736d1210a39c2547cb9d90e","5736d1380a39c2547cb9d90f]
var array2 = []
array1.forEach(function(stringId){
array2.push(new ObjectID(stringId)))
})
then use this array2 variable in query
db.coll.find({
_id: {
$in: array2
}
}).toArray(function(err, docs) {
console.log(docs);
res.send(docs)
});
Upvotes: 2
Reputation: 7654
I don't know much about mongoskin but may be you can try this...
var newArray = oldArray.map(function(ele) {
return mongoskin.helper.toObjectID(ele);
});
OR
var newArray = oldArray.map(mongoskin.helper.toObjectID(ele));
So now you may use newArray in your query
db.coll.find({
_id: {
$in: newArray
}
}).toArray(function(err, docs) {
console.log(docs);
res.send(docs)
});
Upvotes: 4