Hello
Im current in fullstack course and Im having problem appropriating a framework for seeding data inside collections. It creates consumer and tickets collections however json to schema data does not get sent / get reject. Im quite green.
Seeder.js
const fs = require('fs')
const path = require('path')
const db = require('../server/ModelHandler')
const mongoose = require('mongoose')
module.exports = class Seeder {
static async seed() {
await db.connect()
await mongoose.connection.db.dropDatabase()
console.log('\n\nSEEDING DB\n' + '-'.repeat(60) + '\n')
await this.insertData()
console.log('\n\nAll done!\n');
process.exit();
}
static async insertData() {
let allCustomers = []
let data = this.readJsonFiles('./', 'data')
for (let [route] of data) {
let model = db.modelsByApiRoute[route]._model;
if (!model) {
throw (new Error(`Model for collection ${route} not found.`));
}
if (route === 'customers') {
console.log('customers working')
rows.forEach(x =>
x.customerId = x.customerId === null ? null : allCustomers[x.customerId - 1]);
}
console.log(`Inserted data in the ${route} collection.`);
}
}
}```
ModelHandler.js / seems to format the json to schema via a template.
const fs = require(‘fs’)
const path = require(‘path’)
const mongoose = require(‘mongoose’)
module.exports = class ModelHandler {
static types = mongoose.Schema.Types
static modelsByApiRoute = {}
static modelsByName = {}
static async connect() {
global.db = this
await mongoose.connect(require('./secrets/dbCredentials.json'))
this.getAllModels()
}
static getAllModels() {
let modelsPath = path.join(__dirname, 'models')
fs.readdirSync(modelsPath).sort()
.filter(x => x.slice(-3) === '.js')
.map(x => path.join(modelsPath, x))
.forEach(x => require(x))
this.finalizeSchemasAndModels()
}
static registerModel(settings) {
this.modelsByApiRoute[settings.apiRoute] = settings
this.modelsByName[settings.model] = settings
}
static finalizeSchemasAndModels() {
for (let x of Object.values(this.modelsByName)) {
let { collection } = x;
let schemaProps = x.schemaProperties
|| this.modelsByName[x.schemaPropertiesFrom].schemaProperties;
let schema = new mongoose.Schema(schemaProps, { collection });
x.addHooks && x.addHooks(schema);
let model = mongoose.model(x.model, schema);
console.log('Model ' + x.model + ' created');
x._model = model;
}
}
}
The data itself
json - > template
[
{
"customerName": "aderges0@cnet.com",
"email": "Arleta",
"telephoneNumber": "16"
},
{
"customerName": "aderges0@cnet.com",
"email": "Arleta",
"telephoneNumber": "16"
},
{
"customerName": "aderges0@cnet.com",
"email": "Arleta",
"telephoneNumber": "6"
}
]
the template
customer for example
db.registerModel({
model: ‘Customer’,
collection: ‘customers’,
apiRoute: ‘customers’,
readOnly: false,
schemaProperties: {
customerName: { type: String, required: true },
email: { type: String, required: true },
telephoneNumber: {type: String, required: true}
},
addHooks(schema) { }
})