插件(plugins)
原文:Plugins 翻译:小虾米(QQ:509129)
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,打上mongoose的标签会在我们的搜索结果页面显示。
下一步
现在我们已经掌握了插件和如何参与到伟大的社会成长周围,让我们来看看如何可以帮助贡献Mongoose本身的不断发展。
Last updated
Was this helpful?