A more modern approach that uses async
/await
:
const cursor = db.collection("foo").find({});
while(await cursor.hasNext()) {
const doc = await cursor.next();
// process doc here
}
Notes:
- This may be even more simple to do when async iterators arrive.
- You’ll probably want to add try/catch for error checking.
- The containing function should be
async
or the code should be wrapped in(async function() { ... })()
since it usesawait
. - If you want, add
await new Promise(resolve => setTimeout(resolve, 1000));
(pause for 1 second) at the end of the while loop to show that it does process docs one after the other.