Skip to content

Instantly share code, notes, and snippets.

@bayleedev
Last active December 26, 2019 09:11
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bayleedev/9d32df6477dae2dbc38a to your computer and use it in GitHub Desktop.
Save bayleedev/9d32df6477dae2dbc38a 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
});
@leeya018
Copy link

Ok,
just find out my problem
the function should be added to the schema before creating the model

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment