Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/moeriki/mongo-iterable-cursor

Turn your mongodb cursor into an async iterable.
https://github.com/moeriki/mongo-iterable-cursor

async es2017 iterable mongodb

Last synced: 7 days ago
JSON representation

Turn your mongodb cursor into an async iterable.

Awesome Lists containing this project

README

        


mongo-iterable-cursor


Turn your mongodb cursor into an async iterable.




npm version


Build Status


Coverage Status


dependencies Status

Async iteration is a stage-3 proposal. Use with caution!

## Without babel

You'll need Node.js 4 or above.

```js
const { MongoClient } = require('mongodb');
const iterable = require('mongo-iterable-cursor');

MongoClient.connect('mongodb://localhost:27017/test')
.then((db) => {
const users = db.collection('users');

for (const pendingUser of iterable(users.find())) {
pendingUser.then((user) => {
// handle user
});
}
})
;
```

You can use [for-await](https://www.npmjs.com/package/for-await) to handle your items serially.

```js
const forAwait = require('for-await');
const { MongoClient } = require('mongodb');
const iterable = require('mongo-iterable-cursor');

MongoClient.connect('mongodb://localhost:27017/test')
.then((db) => {
const users = db.collection('users');
return forAwait((user) => {
// handle user
}).of(iterable(users.find()));
})
;
```

## With babel

Your setup needs to support async generator functions. If you are using Babel you'll need at least the following config.

```js
{
"presets": ["es2017"], // or use Node.js v8 which includes async/await
"plugins": [
"transform-async-generator-functions"
]
}
```

```js
const iterable = require('mongo-iterable-cursor');
const { MongoClient } = require('mongodb');

(async () => {
const db = await MongoClient.connect('mongodb://localhost:27017/test');
const users = db.collection('users');

for await (const user of iterable(users.find())) {
//
}
})();
```

## Register

Requiring `mongo-iterable-cursor/register` adds `[Symbol.asyncIterator]` to the [mongodb cursor](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html) `Cursor.prototype`.

```js
require('mongo-iterable-cursor/register');

const { MongoClient } = require('mongodb');

(async () => {
const db = await MongoClient.connect('mongodb://localhost:27017/test');
const users = db.collection('users');

for await (const user of users.find()) {
//
}
})();
```