title: NodeJs MongoDB Nested Queries - Run Callback Synchronously
body: <p>I have a code block like below. I could not find how to achieve that.<br/>
  - I have rooms collection in mongodb and documents in this collection include user id array. Each room can have multiple users.<br/>
  - So I want to find that usernames which are in the rooms that include my user Id.</p>
  
  <p>DB collections:<br/>
  Rooms {roomId:1, users:[99, 100]}, {roomId:2, users:[99, 101]}<br/>
  Users {_id:99, name:"Alex"},{_id:100, name:"Harry"},{_id:101, name:"Tom"}</p>
  
  <pre><code>var userId = 99;
  var arrUserIds = [];
  var arrRooms = [];
  var strUserNames = "";
  db.collection("rooms").find({"users.userId":userId}).toArray(function(err, rooms) {
  
      for (var i=0; i&lt;rooms.length; i++) {
          arrUserIds = [];
  
          for(var j=0; j&lt;rooms[i].users.length; j++){
              arrUserIds.push(new BSON.ObjectID(rooms[i].users[j].userId));   
          }
  
          db.collection('users').find({"_id": {$in: arrUserIds}}).toArray(function(err, users) {
              strUserNames = users.map(function(elem){return elem.name;}).join(", ");
              arrRooms.push({_id:rooms[i].roomId, name:strUserNames });
          });
  
      }
  
      res.json({rooms:arrRooms});
  });
  </code></pre>
  
  <p>I want to have a result like that: <br/>
  arrRooms: [ { _id:1:, name:"Alex, Harry" }, { _id:2:, name:"Alex, Tom" } ]</p>
  
  <p>Thanks</p>