DEV Community

Željko Šević
Željko Šević

Posted on • Originally published at sevic.dev on

Cursor-based iteration with Mongoose

Using cursor-based iteration can be useful when there is a need to iterate (in memory) over all of the documents from a collection and every document is a big object. Every document can be projected to return only specific fields.

const cursor = Model.find().select('/* several fields */').cursor();

for (let document = await cursor.next(); document != null; document = await cursor.next()) {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

Course

Build your SaaS in 2 weeks - Start Now

Top comments (1)

Collapse
 
maurerkrisztian profile image
Krisztián Maurer

Thanks, that was helpful. I don't understand why Mongoose doesn't have a ".hasNext()" function, that could be used to iterate more nicely.