title: Iterating multiple collections in MongoDB using the Node.jS driver and comparing results
body: <p>I have two collections in a MongoDB database: "photos" and "albums".</p>
  
  <p>Each document in the albums collection contains an "images" property which contains an array of ids which are a key back to the photos collection.</p>
  
  <p>Using the Node.js driver I need to iterate over the albums collection and remove orphan images, i.e. images which are not in any album.</p>
  
  <p>I can't seem to figure it out... this is the code I've written</p>
  
  <pre><code>var MongoClient = require('mongodb').MongoClient;
  
  MongoClient.connect('mongodb://localhost:27017/photosharing', function(err, db) {
      if(err) throw err;
  
      var images = db.collection('images');
      var albums = db.collection('albums');
      var myArray = [];
  
      db.albums.count({}, function(err, count) {
          if(err) throw err;
          console.dir("start length of albums is " + count);
      });
  
      images.find({}).toArray(function(err, docs) {
          if(err) throw err;
  
          for (var i=1; i&lt;=docs.length; i++) {
  
              albums.count({"images": i}, function(err, count) {
                  if(err) throw err;
  
                  if ( count == 0 ) {
                      images.remove({images.find({ "_id": i })})
                  }
              });
  
          };    
      });
  
      db.albums.count({}, function(err, count) {
          if(err) throw err;
          console.dir("end length of albums is " + count);
      });
  
      db.close();
  
    });
  </code></pre>