我可以在模型创建之后添加一个mongoose插件吗?

时间:2023-01-20 21:11:50

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.

我有一种情况,我需要在mongoose模型中添加一个插件,但是在每次使用它时,都可能会更改传递给该插件的选项。

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?

有什么方法可以做到这一点吗?

1 个解决方案

#1


2  

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:

在发布后不久,我发现在将插件附加到模式之后,我可以调用我的模型上的compile,例如:

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

#1


2  

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:

在发布后不久,我发现在将插件附加到模式之后,我可以调用我的模型上的compile,例如:

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