简体   繁体   中英

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?

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) => {...});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM