Dynamically add custom instance methods to a mongoose schema Dynamically add custom instance methods to a mongoose schema mongoose mongoose

Dynamically add custom instance methods to a mongoose schema


Caveat coder. It is possible, and whether or not it's a good idea is left as an exercise for the reader.

Your schema is of course affected by the schema object, not any particular instance of your model. Thus, if you want to modify the schema, you'll need to have access to the schema itself.

Here's an example:

var mongoose = require('mongoose')  , db       = mongoose.connect("mongodb://localhost/sandbox_development")var schema = new mongoose.Schema({  blurb: String})var model = mongoose.model('thing', schema)var instance = new model({blurb: 'this is an instance!'})instance.save(function(err) {  if (err) console.log("problem saving instance")  schema.add({other:  String})  // teh secretz  var otherInstance = new model({blurb: 'and I am dynamic', other: 'i am new!'})  otherInstance.save(function(err) {    if (err) console.log("problem saving other instance", err)    process.exit(0)  })})

Notice the call to schema.add which Schema calls internally when you make a new one.