# 插件(plugins)
> 原文:[Plugins](http://mongoosejs.com/docs/plugins.html)
## Plugins
Schemas是可插拔的,那就是,他們允許使用預包裝的能力,擴展他們的功能。這是一個非常強大的功能。
假設我們有幾個集合在我們的數據庫中,并要為每一個添加最后修改的功能。有了插件,這是很容易。只需要創建一個插件一次,并將其應用到每個Schemas:
```
// 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);
```
我們剛剛添加了最后修改的行為對我們的`Game`和`Player`的schemas,并聲明了一個在我們的Games上的lastMod索引。不壞的幾行代碼。
### 全局的Plugins
想注冊一個插件為所有schemas嗎?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);
```
### 社區!
你不僅可以在自己的項目架構功能重復使用也可以從Mongoose社區中獲利。任何插件發布到[NPM](https://npmjs.org/),打上mongoose的[標簽](https://npmjs.org/doc/tag.html)會在我們的[搜索結果](http://plugins.mongoosejs.io/)頁面顯示。
### 下一步
現在我們已經掌握了插件和如何參與到偉大的社會成長周圍,讓我們來看看如何可以幫助[貢獻](https://github.com/Automattic/mongoose/blob/master/CONTRIBUTING.md)Mongoose本身的不斷發展。