Skip to content

Instantly share code, notes, and snippets.

@mikekunze
Created October 19, 2013 14:58
Show Gist options
  • Save mikekunze/7057021 to your computer and use it in GitHub Desktop.
Save mikekunze/7057021 to your computer and use it in GitHub Desktop.
We can do some fun stuff in Node.JS with asynchronous programming. With closures, we can pull a document collection from a NoSQL database, manipulate the results, and push it to an array stored via closure in the parent scope.
require './nosql'
require 'async'
# new results array. this will be available via closure
results = []
# Start the NoSQL connection
nosql.connect ()->
# Get the collection pointer
collection = nosql.getCollection 'collection'
# Find the documents
collection.find {}, (documents)->
# Create our iterator fn to be consumed by the async library
eachDocument = (doc, cb)->
# Do something to doc; add/remove/modify variables.
# Push it to the results array that is in a
# parent scope and available via closure.
results.push doc
async.forEach documents, eachDocument, ()->
# At this point, we have finished getting and dealing with documents.
# We can close the db and deal with the results.
nosql.close()
# If we were writing this in an express route, use res.send
res.send { success: true, results: results }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment