Skip to content

Instantly share code, notes, and snippets.

@supershabam
Last active December 22, 2015 20:59
Show Gist options
  • Save supershabam/6530350 to your computer and use it in GitHub Desktop.
Save supershabam/6530350 to your computer and use it in GitHub Desktop.
var format = require('util').format
, MongoClient = require('mongodb').MongoClient
, mongo_uri = process.env.MONGOHQ_URL
, villians = process.argv.slice(2)
// TODO customize these for your needs
var mongo_options = {
w: 1, // write concern
slaveOk: true // send reads to secondaries
}
MongoClient.connect(mongo_uri, mongo_options, function(err,db) {
// TODO do proper error handling
if (err) { return console.error(err) }
// ensure that superman is in collection
// give superman a fan every time we update
// add villians provided on command-line
var query = {name: 'superman'}
, update = {$inc: {fan_count: 1}, $addToSet: {villians: {$each: villians}}}
, options = {upsert: true}
db.collection('superheros').update(query, update, options, function(err, result) {
if (err) { return console.error(err) }
// how many fans does superman have?
db.collection('superheros').findOne(query, function(err, doc) {
if (err) { return console.error(err) }
console.log(format('superman has %d fans', doc.fan_count))
if(doc.villians.length) {
console.log(format('superman is fighting villians: %s', doc.villians.join(', ')))
}
// allow program to exit by clearing up db resources
db.close()
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment