Last active
December 26, 2019 09:11
-
-
Save bayleedev/9d32df6477dae2dbc38a to your computer and use it in GitHub Desktop.
A better syntax for mongoose instance and static methods.
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'); | |
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
Ok,
just find out my problem
the function should be added to the schema before creating the model