Using mongoskin, I can do a query like this, which will return a cursor:
myCollection.find({}, function(err, resultCursor) {
resultCursor.each(function(err, result) {
}
}
However, I'd like to call some async functions for each document, and only move on to the next item on the cursor after this has called back (similar to the eachSeries structure in the async.js module). E.g:
myCollection.find({}, function(err, resultCursor) {
resultCursor.each(function(err, result) {
externalAsyncFunction(result, function(err) {
//externalAsyncFunction completed - now want to move to next doc
});
}
}
How could I do this?
Thanks
UPDATE:
I don't wan't to use toArray()
as this is a large batch operation, and the results might not fit in memory in one go.
You can do something like this using the async lib. The key point here is to check if the current doc is null. If it is, it means you are finished.
You could use simple setTimeOut's. This is an example in typescript running on nodejs (I am using promises via the 'when' module but it can be done without them as well):
This works with large dataset by using setImmediate:
You can get the result in an
Array
and iterate using a recursive function, something like this.Edit:
This is only applicable for small datasets, for larger one's you should use cursors as mentioned in other answers.
If you don't want to load all of the results into memory using toArray, you can iterate using the cursor with something like the following.
You could use a Future: