Skip to content

Instantly share code, notes, and snippets.

@jackboberg
Last active April 11, 2017 20:39
Show Gist options
  • Save jackboberg/79635e455587472a9448e0ff08781441 to your computer and use it in GitHub Desktop.
Save jackboberg/79635e455587472a9448e0ff08781441 to your computer and use it in GitHub Desktop.
asynchronously iterate on mongodb records
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()
})
})
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)
}
@jackboberg
Copy link
Author

mongo-each provides a similar process, but does not collect and yield results for each iteration

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment