-
-
Save skatesham/63214fbe9a6ba49c386f1c96306295a6 to your computer and use it in GitHub Desktop.
simple DAO example for nodejs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongo = require('mongodb'), | |
EventEmitter = require('events').EventEmitter; | |
function Connector(settings) { | |
settings.port = settings.port || mongo.Connection.DEFAULT_PORT; | |
this.settings = settings; | |
this.server = new mongo.Server(settings.host, settings.port); | |
this.db = new mongo.Db(settings.database, this.server, {native_parser: true}); | |
} | |
Connector.prototype = new EventEmitter(); | |
Connector.prototype.connect = function() { | |
var that = this; | |
this.db.open(function(err, db) { | |
if (err) return that.emit('error', err); | |
that.emit('ready', db); | |
}); | |
} | |
function CategoryRepository(db) { | |
this.db = db; | |
} | |
CategoryRepository.prototype = new EventEmitter(); | |
CategoryRepository.prototype.initialize = function() { | |
var that = this; | |
this.db.collection('categories', function(error, collection) { | |
that.collection = collection; | |
that.emit('ready', that); | |
}); | |
} | |
CategoryRepository.prototype.findAll = function(callback) { | |
return this.db.collection('categories', onCollectionReady); | |
function onCollectionReady(error, collection) { | |
if (error) return callback(error); | |
collection.find(onCursorReady); | |
} | |
function onCursorReady(error, cursor) { | |
console.log('onCursorReady'); | |
if (error) return callback(error, null); | |
cursor.toArray(callback); | |
} | |
} | |
function main() { | |
var connector = new Connector({server:'localhost', database:'learntrack'}); | |
connector.on('ready', function() { | |
var repo = new CategoryRepository(connector.db); | |
repo.on('ready', onRepositoryReady); | |
return connector.connect(onConnectionOpen); | |
function onConnectionOpen(err, db) { | |
console.log('connected'); | |
repo.initialize(); | |
} | |
function onRepositoryReady(repo) { | |
repo.findAll(onQueryResult); | |
} | |
function onQueryResult(err, items) { | |
console.log('got results'); | |
console.dir(items); | |
connector.db.close(); | |
} | |
} | |
connector.connect(); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment