Search code examples
node.jsmongodbmongoskin

mongodb node.js finding document with multiple Ids present in an Array


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

Solution

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