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

设置Mongoose连接时,.then()中的console.log()为什么没有打印输出?

问题原因分析
  • 最核心的原因是 mongoose.connect() 返回的 Promise 一直处于**pending(待定)**状态,没有被 resolve 也没有被 reject,所以既不会触发 .then() 里的打印逻辑,也不会触发 .catch() 的错误输出。
    这种情况绝大多数是因为本地的 MongoDB 服务没有正常启动:Mongoose 默认配置下连接超时时间为30秒,超时前会一直重试连接,不会直接抛出错误结束 Promise,如果你没有等够30秒就手动终止了程序,或者服务确实没有启动,都会卡在 await mongoose.connect(...) 这一行,没有后续输出。
  • 次要问题是你混用了 await 和 .then() 的写法,虽然语法上不报错,但不符合异步逻辑的最佳实践,容易出现逻辑歧义,建议统一写法:
    要么纯用 .then() 链式调用:
    const mongoose = require("mongoose");
    
    function main() {
        mongoose.connect("mongodb://localhost:27017/movieApp")
        .then(() => {
             console.log("CONNECTION OPEN");
        })
        .catch((err) => console.log(err))
    }
    main()
    
    要么纯用 async/await 语法:
    const mongoose = require("mongoose");
    
    async function main() {
        try {
            await mongoose.connect("mongodb://localhost:27017/movieApp")
            console.log("CONNECTION OPEN");
        } catch (err) {
            console.log(err)
        }
    }
    main()
    
排查步骤
  • 先检查本地 MongoDB 服务是否正常启动,Windows 可以在服务列表里找 MongoDB 服务查看运行状态,macOS/Linux 可以执行 ps aux | grep mongod 命令查看进程是否存在。
  • 可以给 Mongoose 连接添加短超时配置,避免 Promise 长时间 pending,方便快速排查问题,示例配置如下:
    await mongoose.connect("mongodb://localhost:27017/movieApp", {
      serverSelectionTimeoutMS: 3000 // 3秒没连上就主动抛错
    })
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 16:45:00