divby0
divby0

Reputation: 67

How do MongoDB cursors work when used with Node.js?

I am using Node.js with the npm package mongodb. When I use findOne(...), I get a result which is directly the item I searched for. When I use find(...) instead, I don't get an array of elements, I get a cursor which looks very weird if you console.log it.

My question is why does it return a cursor instead of the array of elements and is the cursor.forEach(...) call then asynchronous or how can the client get data out of the cursor?

Upvotes: 0

Views: 53

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311895

It returns a cursor instead of an array to provide flexibility to the client to access the results in whatever way is optimal for its needs.

To get an array of all results, you can call the async toArray method on the cursor:

collection.find({...}).toArray((err, docs) => {...});

Same thing for aggregate:

collection.aggregate([{$match: {...}}]).toArray((err, docs) => {...});

Upvotes: 1

Related Questions