Plugins

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:

  1. // lastMod.js
  2. module.exports = exports = function lastModifiedPlugin (schema, options) {
  3. schema.add({ lastMod: Date })
  4. schema.pre('save', function (next) {
  5. this.lastMod = new Date
  6. next()
  7. })
  8. if (options && options.index) {
  9. schema.path('lastMod').index(options.index)
  10. }
  11. }
  12. // game-schema.js
  13. var lastMod = require('./lastMod');
  14. var Game = new Schema({ ... });
  15. Game.plugin(lastMod, { index: true });
  16. // player-schema.js
  17. var lastMod = require('./lastMod');
  18. var Player = new Schema({ ... });
  19. Player.plugin(lastMod);

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.

Global Plugins

Want to register a plugin for all schemas? The mongoose singleton has a .plugin() function that registers a plugin for every schema. For example:

  1. var mongoose = require('mongoose');
  2. mongoose.plugin(require('./lastMod'));
  3. var gameSchema = new Schema({ ... });
  4. var playerSchema = new Schema({ ... });
  5. // `lastModifiedPlugin` gets attached to both schemas
  6. var Game = mongoose.model('Game', gameSchema);
  7. var Player = mongoose.model('Player', playerSchema);

Community!

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 and tagged with mongoose will show up on our search results page.

Next Up

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 to the continuing development of Mongoose itself.