Modifying a model after it has been registered in mongoose #1953

TheNeikos opened this Issue Mar 10, 2014 · 3 comments


None yet
3 participants

Is there a way to modify a model after it has been saved? To explain a bit why I want this:

I am currently working on an extendible Application and I want to offer the ability to change for example the default User Model. For example by adding a custom validation. I could delay the registering of the model until all the extensions have been loaded but it would add some complexity.

So the question I have is if there is a way to change the model (instance methods as well as validation etc..) afterwards.

I don't seem to find anything relating to this in the API.

I have tried a few quick attempts but they failed. (Notably changing the .schema of a model and changing the original model. It was somewhat expected though.)

For completeness:

var UserSchema = new Schema({
    name: {
        type: String,
        required: true
    password_hash: {
        type: String,
        required: true
    password_salt: {
        type: String,
        required: true
    sessions: [SessionSchema]

UserSchema.methods.test = function(){
    console.log('Not what I want');

var UserModel = mongoose.model('User', UserSchema);

// In a seperate file that is loaded later on
var User = require('mongoose').model('User');

User.schema.methods.test = function(){
    console.log('I want this to be displayed');

var user = new User({name: 'sd', password_hash:'sd', password_salt:'sdsd'});
user.test(); // This prints out 'Not what I want'

mleanos commented Dec 5, 2015

@TheNeikos Have you found a solution to this requirement?

I have similar requirement. Where I want to decouple the definition of the actual model, from the pre, post, statics, and methods of my models.

When my application starts, I will first load all model definitions & register them with Mongoose. Then after that has completed, I will load my model configurations (pre, post, statics, etc.).

I'm doing this, so that I can for instance reference a different model from within one of my pre/post hooks, for atomicity & data integrity cleanup.

@mleanos Sorry, I didn't, and dropped the project shortly afterwards.


vkarpov15 commented Dec 5, 2015

We don't currently support modifying hooks, methods, etc. after the model is compiled. Compiling a model is a heavy operation, we might be able to support modifying methods after the fact, but modifying hooks after compilation is dangerous and I wouldn't recommend it.

Accessing a different model in a schema's pre hooks is pretty easy. You can just mongoose.model('modelName');, you can require() in the model, you can use a dependency injection framework, there's numerous alternatives for doing what you're trying to do.

@vkarpov15 vkarpov15 closed this Dec 5, 2015

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