0
I have an API in Nodejs where I created a file to be my datasource, in this file I autoload my models by reading the files of my app and for each matter in the sequelize. The code is this:
import Sequelize from 'sequelize';
import fs from 'fs';
import path from 'path';
let database = null;
// load all model files into models, to import in sequelize
const loadModels = (sequelize) => {
const dir = path.join(__dirname, '../src/');
const models = [];
fs.readdirSync(dir).forEach((subDir) => {
const subDirFiles = path.join(dir, subDir);
fs.readdirSync(subDirFiles).forEach((file) => {
if (file.indexOf('model.js') !== -1) {
const modelFile = path.join(subDirFiles, file);
const model = sequelize.import(modelFile);
models[model.name] = model;
}
});
});
return models;
};
export default (app) => {
if (!database) {
const config = app.config;
const op = Sequelize.Op;
const sequelize = new Sequelize(
...
);
database = {
sequelize,
Sequelize,
models: {},
};
database.models = loadModels(sequelize);
sequelize.sync().done(() => database);
}
return database;
};
My question is how to make this same autoload of models for Mongoose?
I already updated my datasource but I can’t autoload the model, the structure of my Model file receives the connection and the Mongoose in the constructor, this way:
export default (conn, mongoose) => {
const Users = conn.model(collection.Users, new mongoose.Schema({
name: {
type: String,
required: true,
}));
return Users;
};
Any idea how to fix this?
Thanks Odirlei, your source helped me, good solution. :)
– Daniel Castro