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);
  • 相关阅读:
    矩阵快速幂模板
    POJ 3761 Bubble Sort 快速幂取模+组合数学
    MySQL批量修改表前缀
    js生成条形码插件
    如何将本地代码通过git上传到码云
    jQuery常用方法
    MySQL按日、周、月统计数据
    PHP文件下载
    python报错ModelNotFoundError
    thinkphp生成的验证码提示因存在错误无法显示
  • 原文地址:https://www.cnblogs.com/surahe/p/5197005.html
Copyright © 2011-2022 走看看