iyf
iyf

Reputation: 31

Mongoose: How to add multiple plugins

In Mongoose, I've never actually seen an example of setting multiple Mongoose plugins on a schema. All I ever see is

schema.plugin(mongooseSearchPlugin);

How does one go about adding another plugin to that? e.g. mongoosePaginatePlugin?

Upvotes: 3

Views: 2083

Answers (2)

stetson
stetson

Reputation: 145

Unfortunately mongoose doesn't support initializing multiple plugins at once. So the only option is to call schema.plugin(...) multiple times.

You can can call the function multiple times to initialize all your plugins like this:

schema.plugin(mongooseSearchPlugin);
schema.plugin(mongoosePaginatePlugin);

Alternatively, if you store your functions in an iterable (something like an array) you can just iterate over each item and initialize it that way. Something like this:

const myPlugins = [ mongooseSearchPlugin, mongoosePaginatePlugin ];

myPlugins.forEach(plugin => schema.plugin(plugin));

// Or you can you block style
myPlugins.forEach((plugin) => {
    schema.plugin(plugin);
});

Depending on how many plugins you're using this might make your code shorter. Ultimately it's a styling choice.

Hope this explanation helped.

Upvotes: 5

Arvydas
Arvydas

Reputation: 91

Simply call schema.plugin multiple times

Upvotes: 2

Related Questions