How to iterate over a MongoDB cursor serially with Node.js?

Sometimes, we want to iterate over a MongoDB cursor serially with Node.js.

In this article, we’ll look at how to iterate over a MongoDB cursor serially with Node.js.

How to iterate over a MongoDB cursor serially with Node.js?

To iterate over a MongoDB cursor serially with Node.js, we can use the cursor.hasNext method.

For instance, we write

const cursor = db.collection("foo").find({});
while (await cursor.hasNext()) {
  const doc = await cursor.next();
  // ...
}

to call cursor.hasNext which returns a promise.

Then we use await to wait for hasNext to return a result.

If the promise resolves to truer, then we run the loop body.

We get cursor from making a query with find.

Conclusion

To iterate over a MongoDB cursor serially with Node.js, we can use the cursor.hasNext method.