Reputation: 34627
I know you can define methods and statics on a schema
var schema = new mongoose.Schema({});
schema.methods.fn = function(){}
But is it possible after you've created a model from the schema?
var model = mongoose.model(schema);
I tried
model.schema.methods.fn2 = function(){};
but it doesn't work.
I wanted to add certain methods at runtime, and since the only important thing at runtime is the model, and not the schema, I was wondering if you could continue to add methods to the model's internal schema somehow dynamically?
Upvotes: 3
Views: 1098
Reputation: 4703
You can create a prototype on any registered model by creating a prototype on the model object.
In your model definition file
//define your schema
module.exports = mongoose.model('model', schema);
Anywhere in your app
Use the mongoose object to access the model of your choice and add a method. You can make the model name and the function name a variable, if you'd like:
if (!mongoose.models['model']['fn2']) {
mongoose.models['model'].prototype['fn2'] = function() {
console.log("Yeah!");
}
}
Once this function has been prototyped, simply call the instance function on any document from this model:
model.findById(someId).exec(function(err, doc) {
if (doc) {
if (typeof doc.fn2 === 'function') {
doc.fn2(); //writes "Yeah!" to the console.
}
}
});
Upvotes: 1
Reputation: 8141
Yes, you can add methods to your mongoose model just like you would any other javascript class.
var Person = mongoose.model('Person', PersonSchema);
Person.prototype.myMethod = function() {
console.log(this.toString());
}
var bob = new Person({
name: 'Bob'
});
myModel.myMethod();
Note that capitalizing javascript classes like this is a good convention to follow, it makes it clear to the reader that it's a constructor function that should be called with new
.
Upvotes: 4