CD-jS
CD-jS

Reputation: 1119

Can I add a mongoose plugin to a model after it has been created?

I have a situation where I need to add a plugin to a mongoose model but change the options passed to that plugin potentially every time it is used.

See example below:

const PersonnelSchema = new Schema({
    _id: { type: Schema.ObjectId },
    GivenName: { type: String },
    FamilyName: { type: String }
});
module.exports = mongoose.model('Personnel', PersonnelSchema, 'Personnel');

What I'd like to be able to do is add the plugin at the time of using the model so that I can pass parameters to it.

I've tried adding the plugin to the schema object on the model when using it for example:

 objModel.schema.plugin(mongoosastic, {
                index: strIndexName,
                transform: (data) => {
                    data.TenantDB = strTenantDB;
                    return data;
                }
});

but this only adds the plugin methods to statics on the schema object, and does not initialize the plugin properly on the model.

Is there some way of achieving this?

Upvotes: 3

Views: 1268

Answers (1)

CD-jS
CD-jS

Reputation: 1119

Shortly after posting I found that I can achieve this by calling compile on my model after attaching the plugin to the schema, for example:

objModel.schema.plugin(mongoosastic, objOptions);
return objModel.compile(objModel.modelName, objModel.schema, objModel.collection.name, objModel.db, mongoose);

Upvotes: 5

Related Questions