Autoload of models in Mongoose

0

I have an API in NodeJS where I created a file to be my datasource, in this file I make the autoload of my models reading the files of my app and for each one I import into 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 autoload of models for mongoose?

I have already updated my datasource but I can not autoload the model, the structure of my Model file receives the connection and mongoose in the constructor, like this:

export default (conn, mongoose) => {
  const Users = conn.model(collection.Users, new mongoose.Schema({
    name: {
      type: String,
      required: true,
    }));

  return Users;
};

Any ideas how to resolve this?

    
asked by anonymous 04.06.2018 / 21:33

1 answer

1

Hello, I created a boilerplate for node projects with express + mongodb, I use mongoos as ODM, the modules I import them using express-load and you can take a look at it, I think you can take advantage of this structure. >

link

    
18.06.2018 / 15:21