Skip to content

Instantly share code, notes, and snippets.

@stefanwalther
Forked from bayleedev/mongoose.js
Created December 17, 2016 22:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanwalther/a998f94cfd4df27ef5dc61151706e96f to your computer and use it in GitHub Desktop.
Save stefanwalther/a998f94cfd4df27ef5dc61151706e96f to your computer and use it in GitHub Desktop.
A better syntax for mongoose instance and static methods.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/foobar');
// bootstrap mongoose, because syntax.
mongoose.createModel = function(name, options) {
var schema = new mongoose.Schema(options.schema);
for (key in options.self) {
if (typeof options.self[key] !== 'function') continue;
schema.statics[key] = options.self[key];
}
for (key in options) {
if (typeof options[key] !== 'function') continue;
schema.methods[key] = options[key];
}
return mongoose.model(name, schema);
};
// Define the model w/ pretty syntax!
var Animal = mongoose.createModel('Animal', {
schema: {
name: String,
type: String
},
self: {
findByType: function(type, cb) {
return this.find({ type: type }, cb);
}
},
findSimilarTypes: function(cb) {
return this.model('Animal').find({ type: this.type }, cb);
}
});
// Interaact with it
var dog = new Animal({ type: 'dog' });
dog.findSimilarTypes(function (err, dogs) {
console.log(dogs); // woof
});
Animal.findByType('dog', function(err, dogs) {
console.log(dogs); // ruff
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment