Skip to content

Commit

Permalink
docs(plugins): note that plugins should be applied before you call `m…
Browse files Browse the repository at this point in the history
…ongoose.model()`

Fix #7723
  • Loading branch information
vkarpov15 committed Aug 26, 2020
1 parent 6ec173b commit 54ed471
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions docs/plugins.pug
Expand Up @@ -27,6 +27,7 @@ block content
<ul class="toc">
<li><a href="#example">Example</a></li>
<li><a href="#global">Global Plugins</a></li>
<li><a href="#apply-plugins-before-compiling-models">Apply Plugins Before Compiling Models</a></li>
<li><a href="#official">Officially Supported Plugins</a></li>
</ul>

Expand Down Expand Up @@ -84,6 +85,39 @@ block content
const Player = mongoose.model('Player', playerSchema);
```

<h3 id="apply-plugins-before-compiling-models"><a href="#apply-plugins-before-compiling-models">Apply Plugins Before Compiling Models</a></h3>

Because many plugins rely on [middleware](/docs/middleware.html), you should make sure to apply plugins **before**
you call `mongoose.model()` or `conn.model()`. Otherwise, [any middleware the plugin registers won't get applied](/docs/middleware.html#defining).

```javascript
// loadedAt.js
module.exports = function loadedAtPlugin(schema, options) {
schema.virtual('loadedAt').
get(function() { return this._loadedAt; }).
set(function(v) { this._loadedAt = v; });

schema.post(['find', 'findOne'], function(docs) {
if (!Array.isArray(docs)) {
docs = [docs];
}
const now = new Date();
for (const doc of docs) {
doc.loadedAt = now;
}
});
};

// game-schema.js
const loadedAtPlugin = require('./loadedAt');
const gameSchema = new Schema({ ... });
const Game = mongoose.model('Game', gameSchema);

// `find()` and `findOne()` hooks from `loadedAtPlugin()` won't get applied
// because `mongoose.model()` was already called!
gameSchema.plugin(loadedAtPlugin);
```

<h3 id="official"><a href="#official">Officially Supported Plugins</a></h3>

The Mongoose team maintains several plugins that add cool new features to
Expand Down

0 comments on commit 54ed471

Please sign in to comment.