Created
August 28, 2011 14:04
-
-
Save karlseguin/1176702 to your computer and use it in GitHub Desktop.
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
// account.js | |
var Store = new (require('./store').Store)('accounts', {'_id': 'id', 's': 'secret'}, function(){return new Account();}); | |
var Account = function Account() { | |
this.id = this.secret = null; | |
}; | |
Account.findById = function(id, callback) { | |
Store.findOne({'_id': Store.idFromString(id)}, function(err, result) { | |
if (err) { callback(err); } | |
else { callback(null, result); } | |
}); | |
}; | |
module.exports = Account; | |
//store.js | |
var Mongo = require('mongodb'), | |
Db = Mongo.Db, | |
Connection = Mongo.Connection, | |
Server = Mongo.Server, | |
ObjectID = Mongo.BSONPure.ObjectID; | |
var db = new Db('mongo_stats', new Server('127.0.0.1', 27017, {})); | |
exports.open = function(callback) { | |
db.open(function(err, db) { | |
callback(err, db); | |
}); | |
}; | |
var Store = function Store(collectionName, map, create) { | |
this.collectionName = collectionName; | |
this.map = map; | |
this.create = create; | |
}; | |
Store.prototype.findOne = function(doc, callback) { | |
var self = this; | |
db.collection(this.collectionName, function(err, collection) { | |
if (err) { callback(err); return; } | |
collection.findOne(doc, function(err, result) { | |
if (err) { callback(err); return; } | |
callback(null, self.createInstance(result)); | |
}); | |
}); | |
}; | |
Store.prototype.idFromString = function(str) { | |
return ObjectID.createFromHexString(str); | |
}; | |
Store.prototype.createInstance = function(result) { | |
var o = this.create(); | |
for (var key in result) { | |
o[this.map[key]] = result[key]; | |
} | |
return o; | |
} | |
module.exports.Store = Store; | |
//example.js | |
var Account = require('./account'), | |
Store = require('./store'); | |
Store.open(function(err, db) { | |
Account.findById("4e5894ab50c75b3949c62c76", function(err, account){ | |
console.log(account); | |
}); | |
db.closse(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment