2.0.0 • Published 5 years ago

mongo-iterable-cursor v2.0.0

Weekly downloads
3
License
MIT
Repository
github
Last release
5 years ago

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

Without babel

You'll need Node.js 4 or above.

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 to handle your items serially.

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.

{
  "presets": ["es2017"], // or use Node.js v8 which includes async/await
  "plugins": [
    "transform-async-generator-functions"
  ]
}
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 Cursor.prototype.

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()) {
    //
  }
})();