最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Mongodb猫鼬模型从index.js文件中全部导出它们

运维笔记admin9浏览0评论

Mongodb猫鼬模型从index.js文件中全部导出它们

Mongodb猫鼬模型从index.js文件中全部导出它们

我的项目结构是这样

src
 /models
 -Session.js
 -Screen.js
 -Event.js
 -index.js
 /controllers

只是我想使用我的index.js文件导出所有这些模型。因此,我可以轻松地在我的控制器文件中使用它,像这样

sessionController.js

const db = require('../models')
db.Session.find()

为了实现这一点,我到目前为止已经尝试过了

const fs = require('fs');
const path = require('path');
const db ={}
fs
  .readdirSync(__dirname)
  .filter((file) => file !== 'index.js')
  .forEach(file =>{

  })

module.exports = db;

但是我想不出如何以这种方式导出它们。如何使用node.js实现此目标?

回答如下:

在index.js中,导入所有其他模型文件。

const session = require('./Session');
const event = require('./Event');
const screen = require('./Screen');

然后您可以将它们全部导出为:

module.exports = {session, event, screen};

现在const db = require('../models')将为您提供一个具有所有模型的对象。

发布评论

评论列表(0)

  1. 暂无评论