Search code examples
node.jsmongodbmongoosemongoose-plugins

how to override function of mongoose plugin?


I have a plugin in mongoose and for each schema i am doing the following

var user = new Schema({});
user.plugin(myplugin);
user.statics.createCustomDoc = function() {
.....
}

The problem is the createCustomDoc method is also defined in myplugin. Now i want to override createCustomDoc of myplugin with the method defined as user.statics.createCustomDoc.

Currently the method called is from the plugin not the one i wrote in user.statics.createCustomDoc.

How do i do that.?

Of course i do not want to change the name of function nor i want to remove the plugin nor i want to change code of plugin.


Solution

  • I faced similar issue while overriding mongoose query functions and tried something like this and it works

    //store reference to original myPlugin createCustomDoc function
    var createCustomDoc = user.statics.createCustomDoc;
    
    //override that function
    user.statics.createCustomDoc = function (options, callback) {
       var self = this; 
       //after your code, call original function
       createCustomDoc.call(self, options, callback);
    
    }