# 插件（plugins）

> 原文：[Plugins](http://mongoosejs.com/docs/plugins.html)\
> 翻译：小虾米（QQ:509129）

## Plugins

Schemas是可插拔的，那就是，他们允许使用预包装的能力，扩展他们的功能。这是一个非常强大的功能。

假设我们有几个集合在我们的数据库中，并要为每一个添加最后修改的功能。有了插件，这是很容易。只需要创建一个插件一次，并将其应用到每个Schemas：

```javascript
// 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注册插件。例如:

```javascript
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本身的不断发展。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://mongoose.shujuwajue.com/guide/plugins.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
