今天讲一个常识点插件。不熟悉mongoose的朋友,mongoose里面可能有插件吧?更何况这真的存在。那么,如何在mongoose中使用插件呢?mongoose插件的使用和通常的JavaScript插件一样,用于代码复用。类似于MongooseRecognition(2)中介绍的方法。可以添加到Schema的实例上。首先引入一个apischema.add(),该方法可以实现Schema的扩展。然后,可以仿照mongoose识别(2)中的代码,修改其代码如下:日期,默认值:Date.now},updateAt:{类型:日期,默认值:Date.now}})UserSchema.pre('save',function(next){letnow=Date.now()this.updateAt=now;if(!this.createAt)this.createAt=now;})把createAt和updateAt的代码提取出来,因为在开发中,很多集合都需要它们,它们的处理方法也可能会用到。因此,用插件封装它们就变得很有必要了。可以参考如下代码:module.exports=function(schema){schema.add({createAt:{type:Date,default:Date.now},updateAt:{type:Date,default:Date.now}})架构。pre('save',function(next){letnow=Date.now()this.updateAt=now;if(!this.createAt)this.createAt=now;})}文件名为time-plugin.js那么,在使用它的UserSchema定义中引用它。代码如下:源码中letUserSchema=newmongoose.Schema({firstname:String,lastname:String})lettimePlugin=require('../plugins/time-plugin.js)userSchema.plugin(timePlugin)cnode-club的代码中定义了一个base_model.js文件,在topic.js、user.js等文件中引用了该文件。mongoose系列篇mongoose再认识(一)mongoose再认识(二)mongoose再认识(三)
