Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!