title: Mongodb : find documents including references to sub-documents [node-mongodb-native]
body: <p>I have the following Mongodb Documents : </p>
  
  <pre><code>Users : {'_id' : '12345', 'fullname' : 'ABC'}
  and 
  Files : 
          {'_id' : 'File001', 'path' : 'pathA', 'Users_id' : '12345'}
          {'_id' : 'File002', 'path' : 'pathB', 'Users_id' : '12345'}
  </code></pre>
  
  <p>How do i query or find all 'Files' documents in a way that the 'Users_id' which is referencing to the 'Users' document has the full 'Users' Document?</p>
  
  <p>Expected Output :</p>
  
  <pre><code>{'_id' : 'File001', 'path' : 'pathA', 'Users_id' : '12345', 'user' : {'_id' : '12345', 'fullname' : 'ABC'}}
  {'_id' : 'File002', 'path' : 'pathB', 'Users_id' : '12345', 'user' : {'_id' : '12345', 'fullname' : 'ABC'}}
  </code></pre>
  
  <p>In this way, i could access the file owner's fullname  as such : file.user.fullname</p>
  
  <p>I Appreciate any help from you guys.  Thank you.</p>
  
  <p><strong>--- EDIT</strong></p>
  
  <p>I am using node-mongodb-native to access the db.</p>
  
  <p>Below is my code to retrieve it:</p>
  
  <pre><code>var files = db.collection ('Files');
  
  files.find ({}, {}).toArray (function ( err, filesDoc){
      for ( var index in filesDoc) {
          var fileDoc = filesDoc [ index ];
          var users = db.collection ('Users');
          users.findOne ({'_id' : fileDoc.Users_id}, {}, function (errUser, userDoc){
              if ( ! errUser ) {
                  fileDoc.user = userDoc;
              }
          });
      }
  });
  </code></pre>
  
  <p>but this code is not assigning the user to all files doc and only assigns to the last element of the filesDoc array. Any suggestions?</p>