Mongodb - return an object instead of an array from find

db.users.find(); 

Will return an array of users to me:

 [{ _id: 123 name: bob },{ _id: 456 name: tom }] 

I need to map users to another collection by id, so I would like to return the object back from mongo, where the keys are _id and the values ​​are a user document.

i.e.

 users = { 123: {_id: 123, name: bob}, 456: {_id, 456, name:tom} } 

Then I can access users directly from this object without iterating through the array to find specific users.

 id = 123; user = users[id]; 
+5
source share
2 answers

You cannot get an object like this from mongodb, but it is easy to create one yourself:

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

Placing my solution in more modern syntax:

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

Source: https://habr.com/ru/post/1491284/


All Articles