[译]Mongoose指南

Schema支持插件, 这样你就可以扩展一些额功能了

下面的例子是当document save的时候自定更新最后修改日期的出插件

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

  

原文地址:https://www.cnblogs.com/irocker/p/mongoose-plugin.html