Skip to content

Instantly share code, notes, and snippets.

@heymichaelp
Last active August 29, 2015 14:03
Show Gist options
  • Save heymichaelp/1b6e9ee22e12410be46d to your computer and use it in GitHub Desktop.
Save heymichaelp/1b6e9ee22e12410be46d to your computer and use it in GitHub Desktop.
Query Objects: Example
var _ = require('underscore')
var async = require('async')
var MongoClient = require('mongodb').MongoClient
var CreateStudentQuery = function(student) {
this.student = student
}
CreateStudentQuery.prototype = _.extend(CreateStudentQuery, {
run: function(callback) {
async.waterfall([
_.bind(this.connectToDatabase, this),
_.bind(this.getStudentsCollection, this),
_.bind(this.insertStudent, this),
_.bind(this.closeConnection, this)
], callback)
},
connectToDatabase: function(callback) {
MongoClient.connect(CreateStudentQuery.DATABASE_URL, callback)
},
getStudentsCollection: function(db, callback) {
this.db = db
callback(null, db.collection(CreateStudentQuery.COLLECTION_NAME))
},
insertStudent: function(collection, callback) {
collection.insert(this.student, callback)
},
closeConnection: function(result, callback) {
this.db.close()
callback(null, result)
}
})
CreateStudentQuery.DATABASE_URL = 'mongodb://127.0.0.1:27017/test'
CreateStudentQuery.COLLECTION_NAME = 'students'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment