require all model of mongoose in express app.js

Viewed 307

In my app.js of express app, I always have to include model every time I created a model

require('./models/Users')
require('./models/Projects')

Is there a way to avoid this? something like require('./models/*) ?

3 Answers

using glob to get all file in models path

var glob = require( 'glob' )
  , path = require( 'path' );

glob.sync( './models/**/*.js' ).forEach( function( file ) {
  require( path.resolve( file ) );
});

Using native nodejs, You can read the directory and load/require modules dynamically.

const fs = require("fs");
const path = require("path");
const models = fs.readdirSync("./models/");
models.forEach((dir) => {
  if (fs.statSync(dir).isFile) require(path.join("./models/", dir));
});

Util:

const getModels = (dir) => {
  return fs
    .readdirSync(dir)
    .filter((file) => fs.statSync(file).isFile)
    .map((file) => require(path.join("./models/", file)));
};
module.exports ={getModels}

// How to use

const models = getModels("./models/")

Create a Separate file which will include all the exported module file and just export on objects and use it whenever required,

Related