Tyler James Tyler James -5 years ago 162
Node.js Question

Determine if collection.forEach is done [ mongodb ]

I'm trying to print all data from a collection and some research has shown the best way to do that is

DB.collection('users').find({}).each( (err, i) => {

Which is great, but running a console.log after this loop will print before hand, and I need to run something after all items are returned.

If I can instead retrieve all documents at once, that would solve my issue, otherwise I need to determine when this loop is complete, then run some code to handle the results.

Answer Source

This took a bit of puzzling to figure out, as the MongoDB API directly doesn't directly map on expected Node concepts.

Regardless, MongoDB's find method returns a cursor object. This cursor object does in fact implement each (as well as other helpful methods like toArray.)

However, the callback takes two parameters, not just one. [Edit: the question used to have only one parameter in the callback, a transcription mistake by OP]

DB.collection('users').find({}).each( (error, i) => {

It's Node convention that the first parameter of a callback be an error object, for error handling purposes. The next parameters are your actual data - in this case the record from Mongo.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download