[英]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在我的 express 应用程序的 app.js 中,每次创建 model 时,我总是必须包含 model
require('./models/Users')
require('./models/Projects')
Is there a way to avoid this?有没有办法避免这种情况? something like
require('./models/*)
?类似
require('./models/*)
东西?
Using native nodejs
, You can read the directory
and load/require modules dynamically
.使用本机
nodejs
,您可以读取directory
并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,创建一个单独的文件,其中将包含所有导出的模块文件,并仅导出对象并在需要时使用它,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.