'use strict';
const fs = require('fs');
const path = require('path');
// 转换json,去掉ObjectId( )
function parseJson(fileStr) {
fileStr = fileStr.replace(/ObjectId\(/g, '').replace(/\)/g, '');
return JSON.parse(fileStr);
}
// 读取json
function getJson(modelName) {
try {
const jsonPath = path.join('data', modelName + 's.json');
const fileStr = fs.readFileSync(jsonPath, 'utf-8');
return parseJson(fileStr);
} catch (err) {
console.log(err);
}
return '';
}
// 以更新的方式插入
async function insertJson(target, data) {
const result = await target.findOne({ _id: data._id });
if (result) {
await target.updateOne({ _id: data._id }, { $set: data });
} else {
await target.create(data);
}
}
module.exports = app => {
app.beforeStart(async () => {
const ctx = app.createAnonymousContext();
const model = ctx.model;
for (const key in model) {
const modelName = model[key].modelName;
const data = getJson(modelName);
if (Array.isArray(data)) {
data.forEach(async item => {
await insertJson(model[key], item);
});
} else {
await insertJson(model[key], data);
}
}
});
};
egg mongoose 启动程序初始化数据
最新推荐文章于 2022-03-25 11:34:48 发布