Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *