2017-09-03 08:43:13 +08:00
|
|
|
|
const yapi = require('../yapi.js');
|
|
|
|
|
const mongoose = require('mongoose');
|
|
|
|
|
const autoIncrement = require('mongoose-auto-increment');
|
2017-07-05 16:17:58 +08:00
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 所有的model都需要继承baseModel, 且需要 getSchema和getName方法,不然会报错
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
class baseModel{
|
|
|
|
|
constructor(){
|
2017-07-26 22:03:18 +08:00
|
|
|
|
this.schema = new mongoose.Schema(this.getSchema());
|
|
|
|
|
this.name = this.getName();
|
|
|
|
|
|
2017-07-10 11:56:53 +08:00
|
|
|
|
if(this.isNeedAutoIncrement() === true){
|
|
|
|
|
this.schema.plugin(autoIncrement.plugin, {
|
|
|
|
|
model: this.name,
|
|
|
|
|
field: this.getPrimaryKey(),
|
2017-08-23 16:11:43 +08:00
|
|
|
|
startAt: 11,
|
2017-07-31 10:15:16 +08:00
|
|
|
|
incrementBy: yapi.commons.rand(1, 10)
|
2017-07-26 22:03:18 +08:00
|
|
|
|
});
|
2017-07-10 11:56:53 +08:00
|
|
|
|
}
|
|
|
|
|
|
2017-07-05 16:17:58 +08:00
|
|
|
|
this.model = yapi.db(this.name, this.schema);
|
|
|
|
|
}
|
2017-07-10 11:56:53 +08:00
|
|
|
|
|
|
|
|
|
isNeedAutoIncrement(){
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 可通过覆盖此方法生成其他自增字段
|
|
|
|
|
*/
|
|
|
|
|
getPrimaryKey(){
|
2017-07-26 22:03:18 +08:00
|
|
|
|
return '_id';
|
2017-07-10 11:56:53 +08:00
|
|
|
|
}
|
2017-07-06 19:21:54 +08:00
|
|
|
|
|
2017-07-05 16:17:58 +08:00
|
|
|
|
/**
|
|
|
|
|
* 获取collection的schema结构
|
|
|
|
|
*/
|
|
|
|
|
getSchema(){
|
2017-07-26 22:03:18 +08:00
|
|
|
|
yapi.commons.log('Model Class need getSchema function', 'error');
|
2017-07-05 16:17:58 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
getName(){
|
2017-07-26 22:03:18 +08:00
|
|
|
|
yapi.commons.log('Model Class need name', 'error');
|
2017-07-05 16:17:58 +08:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
module.exports = baseModel;
|