You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express项目问题:Index文件无法正确调用其他依赖文件

问题分析与解决方案

我来帮你排查几个核心问题,这应该能解决你的日志不显示和数据库相关的疑惑:

1. 控制台看不到winston日志的原因

你的logging.js里只配置了文件传输(File transport),没有添加控制台传输(Console transport),所以winston.info()的消息只会写入到logfile.log文件,不会输出到终端。另外,你的index.js里还缺少对winston的引用,直接用winston.info会触发未定义错误,这个错误被logging.js里的异常处理器捕获并写入了uncaughtExceptions.log,所以你终端看不到报错。

修复步骤:

  • 首先在index.js顶部添加winston的引用:
    const winston = require('winston');
    
  • 然后修改logging.js,添加Console transport,让日志同时输出到控制台和文件:
    const winston = require('winston');
    module.exports = function() {
      winston.handleExceptions(
        new winston.transports.File({ filename: 'uncaughtExceptions.log' }),
        // 添加控制台输出未捕获异常
        new winston.transports.Console({ colorize: true, prettyPrint: true })
      );
      process.on('unhandledRejection', (ex) => {
        throw ex;
      });
      // 同时添加文件和控制台传输
      winston.add(winston.transports.File, { filename: 'logfile.log' });
      winston.add(winston.transports.Console, { colorize: true, prettyPrint: true });
    }
    

2. MongoDB数据库未在Compass显示的原因

MongoDB采用懒加载创建数据库的机制:仅仅调用mongoose.connect()只会建立连接,不会自动创建数据库。只有当你向数据库中插入至少一条数据后,数据库才会在Compass中显示出来。

你可以测试一下,比如在连接成功后插入一条测试数据:

// 在db.js的then回调里添加测试代码
mongoose.connect('mongodb://localhost/dwg', {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => {
  winston.info('Connected to MongoDB...');
  // 测试插入数据,触发数据库创建
  const Test = mongoose.model('Test', new mongoose.Schema({ name: String }));
  Test.create({ name: 'test' }).then(() => winston.info('Test data inserted, database created'));
})
.catch(err => console.error("Error connecting to MongoDB:", err))

3. 额外的小检查

确保你的MongoDB服务已经启动,否则mongoose.connect()会失败,这个错误会被catch捕获,建议把错误信息打印出来方便排查:

.catch(err => console.error("Error connecting to MongoDB:", err))

这样修改后,重新用nodemon启动,你应该能在终端看到连接日志、端口监听日志,插入测试数据后Compass里也会出现dwg数据库了。

内容的提问来源于stack exchange,提问作者NodeReact020

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 10:04:05