Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

152
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda