简体   繁体   中英

require all model of mongoose in express app.js

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/*) ?

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/")

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 ) );
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM