Mongodb - Get back object instead of array from find

mongodb, mongoose

Solution

You can't get an object like this one from mongodb, but it's quite easy to build it yourself:

db.users.find(function (err, docs) {
  var users = {};
  docs.forEach(function (doc) {
    users[doc._id] = doc;
  });
  do_whatever_you_want_next(users);
});

Problem

``` db.users.find(); ``` Will return me an array of users: ``` [{ _id: 123 name: bob },{ _id: 456 name: tom }] ``` I need to map users to another collection by the id, so I would like to get an object back from mongo where the keys are _id and values are the user doc. i.e. ``` users = { 123: {_id: 123, name: bob}, 456: {_id, 456, name:tom} } ``` Then I can access users directly from that object without having to iterate an array to find specific users. ``` id = 123; user = users[id]; ```

Original source