Skip to content

Instantly share code, notes, and snippets.

@jrmoran
Created October 28, 2011 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrmoran/1323760 to your computer and use it in GitHub Desktop.
Save jrmoran/1323760 to your computer and use it in GitHub Desktop.
little mongo wrapper for node.js
mongodb = require 'mongodb'
db = {}
options = {}
check_for_errors = (err)->
if err then console.log "#{err}"
# configurate and connect to the database, `options` must be an object
# literal
#
# db : <string>
# host: <string>
# port: <int>
# user: <optional:string>
# pwd : <optional:string>
#
exports.ready = (callback)->
db.open (err, client)->
# authentication
if options.user? and options.pwd?
db.authenticate options.user, options.pwd, (err)->
check_for_errors err
callback()
else
callback()
exports.config = (opts)->
options = opts
server = new mongodb.Server options.host, options.port, auto_reconnect: true
db = new mongodb.Db options.db, server, {}
@
# appends a collection, to the module
exports.collection = (collection)->
db.collection collection, (err, col)-> exports[collection] = col
@
exports.db = db
# Usage
#
# db = require('./mongo')
# db.config
# db: 'industrials'
# host: 'localhost'
# port: 27017
#
# db.ready ->
# db.collection 'daily'
# db.daily.find {symbol: 'IBM'}, (err, results)->
# results.toArray (err, docs)->
# console.log docs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment