zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    asp.net mvc @RenderBody()的问题
    (转)MVC3 类型“System.Web.Mvc.ModelClientValidationRule”同时存在
    Spring配置错误 No adapter for IAdvice of type
    java之路 super
    java之路 static
    java之路 构造代码块注意事项
    java之路 面向对象基础
    Node.js系列02
    Node.js 系列01
    王垠:《程序员的心理疾病》
  • 原文地址:https://www.cnblogs.com/surahe/p/5197005.html
Copyright © 2011-2022 走看看