Skip to content

Instantly share code, notes, and snippets.

@royling
Last active August 29, 2015 14:06
Show Gist options
  • Save royling/7bd9cd237079e1cb2fb8 to your computer and use it in GitHub Desktop.
Save royling/7bd9cd237079e1cb2fb8 to your computer and use it in GitHub Desktop.
use mongoose with co
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!');
});
};
var co = require('co');
var query = require('./query');
require('./connect')();
co(query.list)({}); // find all
co(query.fetchById)('541bbc16f9cf1264094a9524');
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);
};
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