/
plugins.jade
42 lines (34 loc) · 1.82 KB
/
plugins.jade
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
extends layout
block content
h2 Plugins
:markdown
Schemas are pluggable, that is, they allow for applying pre-packaged capabilities to extend their functionality. This is a very powerful feature.
Suppose that we have several collections in our database and want to add last-modified functionality to each one. With plugins this is easy. Just create a plugin once and apply it to each `Schema`:
:js
// lastMod.js
module.exports = exports = function lastModifiedPlugin (schema, options) {
schema.add({ lastMod: Date })
schema.pre('save', function (next) {
this.lastMod = new Date
next()
})
if (options && options.index) {
schema.path('lastMod').index(options.index)
}
}
// game-schema.js
var lastMod = require('./lastMod');
var Game = new Schema({ ... });
Game.plugin(lastMod, { index: true });
// player-schema.js
var lastMod = require('./lastMod');
var Player = new Schema({ ... });
Player.plugin(lastMod);
:markdown
We just added last-modified behavior to both our `Game` and `Player` schemas and declared an index on the `lastMod` path of our Games to boot. Not bad for a few lines of code.
h3 Community!
:markdown
Not only can you re-use schema functionality in your own projects but you also reap the benefits of the Mongoose community as well. Any plugin published to [npm](https://npmjs.org/) and [tagged](https://npmjs.org/doc/tag.html) with `mongoose` will show up on our [search results](http://plugins.mongoosejs.com) page.
h3#next Next Up
:markdown
Now that we've covered plugins and how to get involved in the great community growing around them, let's take a look how you can help [contribute](https://github.com/LearnBoost/mongoose/blob/master/CONTRIBUTING.md) to the continuing development of Mongoose itself.