1234567891011121314151617181920212223242526272829303132333435363738 |
- 'use strict';
- const _ = require('lodash');
- module.exports = data => {
- const { name, name_zh, columns } = data;
- let columnStr = `const ${name} = { \n`;
- let indexStr = '';
- let has_ObjectId = false;
- let has_Secret = false;
- for (let i = 0; i < columns.length; i++) {
- const { title, type, required = false, remark, index } = columns[i];
- const str = ` ${title}: { type: ${type || 'String'}, required: ${required} ${type === 'Secret' ? ', select: false' : ''} }, // ${remark || ''} \n`;
- columnStr += str;
- if (index) indexStr += `schema.index({ '${title}': 1 });\n`;
- if (!has_ObjectId && type === 'ObjectId') has_ObjectId = true;
- else if (!has_Secret && type === 'Secret') has_Secret = true;
- }
- columnStr += '}';
- const nameList = name.split('_');
- const modelName = nameList.map(i => _.capitalize(i)).join('_');
- return `'use strict';
- const Schema = require('mongoose').Schema;
- const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
- ${has_ObjectId ? "const { ObjectId } = require('mongoose').Types;" : ''}
- ${has_Secret ? "const { Secret } = require('naf-framework-mongoose-free/lib/model/schema');" : ''}
- // ${name_zh || ''}
- ${columnStr}
- const schema = new Schema(${name}, { toJSON: { virtuals: true } });
- schema.index({ id: 1 });
- schema.index({ 'meta.createdAt': 1 });
- ${indexStr}
- schema.plugin(metaPlugin);
- module.exports = app => {
- const { mongoose } = app;
- return mongoose.model('${modelName}', schema, ${name});
- };
- `;
- };
|