Last active
April 11, 2017 20:39
-
-
Save jackboberg/79635e455587472a9448e0ff08781441 to your computer and use it in GitHub Desktop.
asynchronously iterate on mongodb records
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { MongoClient } = require('mongodb') | |
const MongoSeries = require('./mongo-run-series') | |
const { host } = process.env // mongodb://localhost:27017/database | |
const task = (doc, done) => { | |
// do something async with the mongodb document | |
done(null, {}) | |
} | |
MongoClient.connect(host, (err, db) => { | |
if (err) throw err | |
const cursor = db.collection('example').find() // some query | |
MongoSeries(cursor, task, (err, results) => { | |
if (err) throw err | |
// results is an array of results from each document | |
console.log(results) | |
db.close() | |
}) | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = (cursor, task, done) => { | |
const results = [] | |
const next = (err, doc) => { | |
if (err || !doc) return done(err, results) | |
process.nextTick(task, doc, (err, result) => { | |
if (err) return done(err) | |
results.push(result) | |
cursor.nextObject(next) | |
}) | |
} | |
cursor.nextObject(next) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
mongo-each provides a similar process, but does not collect and yield results for each iteration