I'm relatively (read: very) new to MongoDB, and am encountering something that's got me confused.
I have an array of Employee objects, each of which looks basically like this:
{
"Name" : "Jack Jackson",
"Title" : "Senior Derp Engineer",
"Specialties" : [
"Kicking",
"Screaming",
"Throwing Tantrums"
]
}
...and I'd like to insert each of them into my collection as a document.
This is the code (simplified):
var collection = db.collection('Employees');
for (var ix=0; ix<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.
}
});
}
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.
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.
Many thanks.
UPDATE: 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.