lostintranslation
lostintranslation

Reputation: 24583

Mongodb - Get back object instead of array from find

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];

Upvotes: 7

Views: 6037

Answers (2)

Miquel
Miquel

Reputation: 8969

Posting my solution in a more modern syntax:

    const pushSubscriptions = await PushSubscription.find({ token: { $in: tokens } }).exec();
    const userTokens = pushSubscriptions.reduce(
        (result, ps) => {
            result[ps.token] = ps;
            return result;
        },
        {});

Upvotes: 1

Leonid Beschastny
Leonid Beschastny

Reputation: 51470

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

Upvotes: 4

Related Questions