I'm new to this javascript thing and have i have some doubts about mongoose 'find' scope's.
I wrote the code below to try to understand the problem.
The code below searches into a Shopping collection and then search for the Stores assigned to this Shopping.
storeMap is a hashmap of storeId => storeObject, but when the Store.findOne scope end, storeMap seems to rollback to an empty array...
var storeMap = {};
Shopping.findOne({ name: shoppingName }, function(err, shopping){
shopping.stores.forEach(function(storeId) {
Store.findOne({_id: storeId}, function(err, store) {
if(err) console.log(err);
console.log(store); //prints out store data
storeMap[storeId] = store;
console.log(storeMap); //prints out store data
});
console.log(storeMap); //prints out an empty array
});
});
So, why my storeMap array is printing an empty array instead of a store array?
Store.findOne, like many things in node.js, is asynchronous and takes a callback. Your callback is where storeMap gets set:
function(err, store) {
if(err) console.log(err);
console.log(store); //prints out store data
storeMap[storeId] = store;
console.log(storeMap); //prints out store data
}
And this only runs once Store.findOne finishes its work, which could take a long time.
The following line, console.log(storeMap); executes immediately, however--before the callback runs. Thus, storeMap is still empty.
I recommend looking at a few examples/explanations of the callback pattern in node.js, it's fundamental to understand.