Autoload models in Mongoose

Asked

Viewed 60 times

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?

1 answer

1


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

https://github.com/borgert-inc/express-api-startkit

  • 1

    Thanks Odirlei, your source helped me, good solution. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.