title: MongoDB / Node.JS: Inserting documents in a loop - variables not updating?
body: <p>I'm relatively (read: very) new to MongoDB, and am encountering something that's got me confused.</p>
  
  <p>I have an array of Employee objects, each of which looks basically like this:</p>
  
  <pre><code>{
    "Name" : "Jack Jackson",
    "Title" : "Senior Derp Engineer",
    "Specialties" : [
      "Kicking",
      "Screaming",
      "Throwing Tantrums"
    ]
  }
  </code></pre>
  
  <p>...and I'd like to insert each of them into my collection as a document.</p>
  
  <p>This is the code (simplified):</p>
  
  <pre><code>var collection = db.collection('Employees');
  for (var ix=0; ix&lt;allEntries.length; ix++) {
    var item = allEntries[ix];
    collection.insert(item, function(err, docs) {
      if (err) { MyErrorCallback(err); }
      else {
        // Insert specialties
        console.log(item["_id"] + ": " + item["Specialties"].length + " specialties.");
        // ...Code goes here which will insert a document into another collection associating the item's ObjectID with each specialty in the list.
      }
    });
  }
  </code></pre>
  
  <p>I'd expect that for a list of 100 Employees, my console output would consist of the newly-created ObjectID for each of the 100 items in allEntries, along with a count of the number of specialties in that item. Instead, what I get is the ObjectID for the first item inserted, and the count of the Specialties for the first item inserted, repeated 100 times.</p>
  
  <p>Why is this? How do I access the just-inserted item including its newly-generated ID, so I can do things with it? This seems like some kind of scoping issue, but it's not making sense to me.</p>
  
  <p>Many thanks.</p>
  
  <p><strong>UPDATE:</strong> 
  I self-answered below with the correct way to retrieve the object; however I'm still very interested if anyone can explain the variable scoping here. It's confusing.</p>