mongoose 文档(九) Plugins

插件

schema是可插入的,即,它们可以应用预包装的能力,从而扩展其功能。这是一个非常强大的功能。

假设我们有几个collection在我们的数据库中,要添加的 last-modified功能给它们。用插件会很容易。只需创建一个插件,并把它应用到每个Schema:

// 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);

 我们刚刚增加last-modified特性到Game和Player schema并声明一个索引到Game的lastMod path来引导。

全局插件

想注册一个给所有shcema的插件?mongoose单例模式的plugin() 函数能给所有schema注册一个插件。 例如:

var mongoose = require('mongoose');
mongoose.plugin(require('./lastMod'));

var gameSchema = new Schema({ ... });
var playerSchema = new Schema({ ... });
// `lastModifiedPlugin` gets attached to both schemas
var Game = mongoose.model('Game', gameSchema);
var Player = mongoose.model('Player', playerSchema);
原文地址:https://www.cnblogs.com/surahe/p/5197005.html