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

Nodemon启动30秒后崩溃,MongoDB连接失败求助

问题描述

nodemon启动后约30秒自动断开,抛出错误[nodemon] app crashed - waiting for file changes before starting...。修改文件后nodemon会自动重启,但闲置约30秒后又会崩溃,服务器无响应,重启后该循环仍持续。完整错误信息显示MongooseServerSelectionError: connect ECONNREFUSED ::1:27017,即无法连接MongoDB的27017端口。已尝试重新安装MongoDB、全局和本地安装nodemon,问题仍存在。

完整错误日志

D:\react\inotebook\backend\node_modules\mongoose\lib\connection.js:792
    err = new ServerSelectionError();
          ^

MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
    at _handleConnectionErrors (D:\react\inotebook\backend\node_modules\mongoose\lib\connection.js:792:11)
    at NativeConnection.openUri (D:\react\inotebook\backend\node_modules\mongoose\lib\connection.js:767:11) {       
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) {
      'localhost:27017' => ServerDescription {
        address: 'localhost:27017',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 15938834,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED ::1:27017
            at connectionFailureError (D:\react\inotebook\backend\node_modules\mongodb\lib\cmap\connect.js:370:20)  
            at Socket.<anonymous> (D:\react\inotebook\backend\node_modules\mongodb\lib\cmap\connect.js:293:22)      
            at Object.onceWrapper (node:events:628:26)    
            at Socket.emit (node:events:513:28)
            at emitErrorNT (node:internal/streams/destroy:151:8)
            at emitErrorCloseNT (node:internal/streams/destroy:116:3)
            at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
          cause: Error: connect ECONNREFUSED ::1:27017    
              at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {
            errno: -4078,
            code: 'ECONNREFUSED',
            syscall: 'connect',
            address: '::1',
            port: 27017
          },
          [Symbol(errorLabels)]: Set(1) { 'ResetPool' }   
        },
        topologyVersion: null,
        setName: null,
        setVersion: null,
        electionId: null,
        logicalSessionTimeoutMinutes: null,
        primary: null,
        me: null,
        '$clusterTime': null
      }
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined
}

Node.js v18.16.0
[nodemon] app crashed - waiting for file changes before starting...

目录结构

React 
|__inotebook
   |__backend
   |  |__node_modules (folder)
   |  |__index.js
   |  |__db.js
   |  |__package-lock.json
   |  |__package.json
   |
   |___ Files and folders created by "npx create-react-app"

相关代码文件

db.js

const mongoose = require('mongoose')
const mongoURI = "mongodb://localhost:27017"

const connectToMongo=()=>{
    mongoose.connect(mongoURI)
    console.log("Connection Successful")
}
 
module.exports=connectToMongo

index.js

const connectToMongo=require('./db')
connectToMongo()

package.json

{
  "name": "inotebook-backend",
  "version": "1.0.0",
  "description": "iNoteboot - Your notebook on the cloud",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2",
    "mongoose": "^7.3.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.22"
  }
}
解决方案

核心问题为MongoDB服务未启动或连接字符串IP解析冲突,按以下步骤处理:

  1. 启动MongoDB服务

    • Windows:按下Win+R输入services.msc打开服务管理器,找到MongoDB服务,右键启动并设置为自动启动。
    • macOS/Linux:执行sudo systemctl start mongod启动服务,sudo systemctl enable mongod设置开机自启。
  2. 修改连接字符串强制使用IPv4
    Node.js 18+默认优先使用IPv6,部分MongoDB未开启IPv6支持,将localhost替换为127.0.0.1:

    // db.js中修改mongoURI
    const mongoURI = "mongodb://127.0.0.1:27017"
    
  3. 添加连接错误监听
    原代码未处理连接失败异常,添加错误捕获避免进程直接崩溃:

    // 修改后的db.js
    const mongoose = require('mongoose')
    const mongoURI = "mongodb://127.0.0.1:27017"
    
    const connectToMongo=()=>{
        mongoose.connect(mongoURI)
            .then(() => console.log("Connection Successful"))
            .catch(err => console.error("Connection Failed:", err))
    }
    
    module.exports=connectToMongo
    
  4. 配置nodemon启动脚本
    在package.json中添加dev脚本,方便启动nodemon:

    // 修改package.json的scripts部分
    "scripts": {
      "start": "node index.js",
      "dev": "nodemon index.js",
      "test": "echo \"Error: no test specified\" && exit 1"
    }
    

    之后执行npm run dev启动项目。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 16:04:54