Skip to content

Instantly share code, notes, and snippets.

@lancelakey
Last active December 17, 2015 22:38
Show Gist options
  • Select an option

  • Save lancelakey/5682970 to your computer and use it in GitHub Desktop.

Select an option

Save lancelakey/5682970 to your computer and use it in GitHub Desktop.
#!/usr/bin/env coffee

# Add document

mongo = require 'mongodb'

server = new mongo.Server "127.0.0.1", 27018, {}

client = new mongo.Db 'test', server

# save() updates existing records or inserts new ones as needed
exampleSave = (dbErr, collection) ->
  console.log "Unable to access database: #{dbErr}" if dbErr
	collection.save { _id: "my_favorite_latte", flavor: "honeysuckle" }, (err, docs) ->
		console.log "Unable to save record: #{err}" if err
		client.close()

client.open (err, database) ->
	client.collection 'coffeescript_example', exampleSave
#!/usr/bin/env coffee

# Find document

mongo = require 'mongodb'

server = new mongo.Server "127.0.0.1", 27018, {}

client = new mongo.Db 'test', server

exampleFind = (dbErr, collection) ->
	console.log "Unable to access database: #{dbErr}" if dbErr
	collection.find({ _id: "my_favorite_latte" }).nextObject (err, result) ->
		if err
			console.log "Unable to find record: #{err}"
		else
			console.log result # => {  id: "my_favorite_latte", flavor: "honeysuckle" }
		client.close()

client.open (err, database) ->
	client.collection 'coffeescript_example', exampleFind
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment