Search code examples
javascriptnode.jses6-promisenode-mongodb-native

Using Promise.all on my db.collection forEach


How can I use promise.all with this function :

function getUsersGroups(users, req) {
  users.forEach(function(user) {
    user.groups = [];

    db.collection("groups")
      .find({ "users._id": String(user._id) })
      .toArray(function(err, docs) {
          user.groups = docs;
      });
  });

  return users;
}

I don't know how to do , thank you.

PS : the users array doesn't get actualized with the docs (they console log ok).

Thi is my second try :

function getUsersGroups(users, req) {
  users.forEach(
    (user, index, array) => (
      array[index].user =[]
      array[index].user.groups = myApiCall(user))
  );

  function myApiCall(user) {
    db.collection("groups")
      .find({ "users._id": String(user._id) })
      .toArray(function(err, docs) {
        console.log(docs);
        return docs;
      });
  }

  return users;
}



  array[index].user.groups = myApiCall(user))
      ^^^^^

SyntaxError: Unexpected identifier

Edit :

So finally, I'm using this function, like Ashish said ( it is getting all of the groups a user is in, and updating the users model) :

async function getUsersGroups(users, req) {
  await Promise.all(users.map(user => {
    return db.collection("groups")
      .find({ "users._id": String(user._id) })
      .toArray()
      .then(group => {
        user.groups = group;
      })
  }));

  return users;
}

And I am calling like this inside of another node.js function :

 getUsersGroups(docs, req)
          .then(users => {
            res.send(users);
          })
          .catch(error => {
            // if you have an error
          });

Thank you a lot !


Solution

  • async function getUsersGroups(users, req) {
      await Promise.all(users.map(user => {
        return db.collection("groups")
          .find({ "users._id": String(user._id) })
          .toArray()
          .then(group => {
            user.groups = group;
          })
      }));
    
      return users;
    }
    

    Hope this helps