2

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) => {
   console.log(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.

1 Answer 1

1

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) => {
   console.log(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.

3
  • Yes, and I'm actually doing this, idk why I didn't in my example given, but that's not the problem I'm having, The problem I'm having is having something run after all results are returned. I have no problem returning the items. Jun 13, 2016 at 0:12
  • then maybe use toArray instead of each? It take a callback with an error and an array of returned records, instead of each record one by one.
    – RyanWilcox
    Jun 13, 2016 at 0:17
  • 1
    Yes! That is exactly what I was looking for, thank you! Jun 13, 2016 at 0:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.