Skip to content

moeriki/mongo-iterable-cursor

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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.

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