I've been trying to figure it out, using the node mongodb native driver, how can I know when a nested collection.find().each() operation is completely done.
Actually, I'm using this to know it:
cursor.find({}).each(function(err, doc) {
// Just a normal example.
if (err) throw err;
if (doc != null) {
console.log(doc);
} else {
console.log("Everything is done")
}
});
It works great until I do something like this:
cursorA.find({}).each(function(err, docA) {
// Just a nested example.
if (err) throw err;
if (docA != null) {
cursorB.find({tags: doc.tag}).each(function(err, docB) {
if (err) throw err;
if (docB != null) {
console.log(docB);
} else {
// It will appear a lot.
console.log("The second part is done.")
}
});
} else {
console.log("The first part is done.")
}
});
It seems to be valid but no. The program will log "The second part is done." per every docA that the previous callback returns. Instead of that, I want to know when the nested find is completely done.
Put it another way, I'd like to see only two logs:
"The first part is done." and 1 "The second part is done." NOT:
"The first part is done." and n "The second part is done."How could I achieve that?
-
Note: I'm using counters to keep the track of the nested operations but it look really messy and/or unappreciated. I think that it could be a better way.