Last active
August 29, 2015 14:06
-
-
Save royling/7bd9cd237079e1cb2fb8 to your computer and use it in GitHub Desktop.
use mongoose with co
This file contains hidden or 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 mongoose = require('mongoose'); | |
var db; | |
var connect = module.exports = function () { | |
mongoose.connect('mongodb://localhost/events'); | |
db = mongoose.connection; | |
db.on('error', function(err) { | |
console.error('Error', err); | |
}); | |
db.once('open', function() { | |
console.log('connected successfully!'); | |
}); | |
}; |
This file contains hidden or 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 co = require('co'); | |
var query = require('./query'); | |
require('./connect')(); | |
co(query.list)({}); // find all | |
co(query.fetchById)('541bbc16f9cf1264094a9524'); |
This file contains hidden or 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 mongoose = require('mongoose'); | |
var Schema = mongoose.Schema; | |
var EventSchema = new Schema({ | |
name: String, | |
_id: Schema.ObjectId | |
}); | |
var Event = mongoose.model('Event', EventSchema); | |
var thunkify = require('./thunkify-model'); | |
var find = thunkify(Event, 'find'); | |
var findById = thunkify(Event, 'findById'); | |
exports.list = function *(conditions) { | |
var docs = yield find(conditions); | |
return docs; | |
}; | |
exports.fetchById = function *(id) { | |
return yield findById(id); | |
}; |
This file contains hidden or 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 thunkify = require('thunkify'); | |
module.exports = function (model, method) { | |
if (!isMongooseModel(model)) throw new TypeError('Can only thunkify a mongoose model'); | |
if ('function' != typeof model[method]) throw new TypeError('No such method found on mongoose model: ' + method); | |
return thunkify(model[method].bind(model)); | |
}; | |
function isMongooseModel(o) { | |
return o && o.model && 'model' === o.model.name; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment