Plug - ins
Schemas are pluggable, that is, they can apply pre-packaged capabilities to extend their functionality. This is a very powerful feature.
Suppose we have several collection in our database, to add the last-modified functionality to them. It's easy to use plugins. Just create a plug-in and apply it to each schema:
//Lastmod.jsModule.exports = exports =functionlastmodifiedplugin (schema, options) {Schema.add ({lastmod:date}) Schema.pre (' Save ',function(next) { This. Lastmod =NewDate Next ()}) if(Options &&options.index) {Schema.path (' Lastmod '). Index (Options.index)}}//Game-schema.jsvarLastmod = require ('./lastmod '));varGame =NewSchema ({...}); Game.plugin (Lastmod, {index:true });//Player-schema.jsvarLastmod = require ('./lastmod '));varPlayer =NewSchema ({...}); Player.plugin (lastmod);
We just added the last-modified feature to the game and player schema and declared an index to the game's lastmod path to boot.
Global plugins
Want to register a plugin for all shcema? The function of Mongoose Singleton mode plugin()
can register a plugin for all schemas. For example:
var mongoose = require (' Mongoose '); Mongoose.plugin (Require ('./lastmod ')); var New Schema ({...}); var New Schema ({...}); // ' Lastmodifiedplugin ' gets attached to both schemas var Game = Mongoose.model (' Game ', Gameschema); var Player = Mongoose.model (' Player ', playerschema);
Mongoose Document (ix) Plugins