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

Node.js连接本地MongoDB后终端卡顿问题求助

连接本地MongoDB后终端卡顿,只能通过Ctrl+C强制终止

尝试连接本地MongoDB数据库并从中获取数据,但建立连接后终端立即卡顿,只能通过Ctrl+C强制终止。已确认连接成功,但Node.js应用出现此问题,此前Python应用可正常连接MongoDB。

我的代码

const express = require('express');
const mongoose = require('mongoose');

const app = express();
const port = 3000;

const dbName = 'inventory';
const dbUrl = `mongodb://localhost:27017/${dbName}`;

// Define the schema and model for the "cars" collection
const carSchema = new mongoose.Schema({
  make: String,
  model: String,
  year: Number
});

const Car = mongoose.model('Car', carSchema);

// Connect to the MongoDB server
mongoose.connect(dbUrl, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {
    console.log(`Connected to database '${dbName}'`);

    // Define a GET route handler that fetches all cars from the database

    app.get('/cars', async (req, res) => {
      try {
        const cars = await Car.find();
        console.log(cars); // Log the fetched cars to the console
        res.json(cars);
      } catch (err) {
        console.error(err);
        res.status(500).send('Server error');
      }
    });

    // Start the Express app
    app.listen(port, () => {
      console.log(`Server is listening on port ${port}`);
    });
  })
  .catch((err) => {
    console.error(err);
  });

MongoDB控制台日志

{"t":{"$date":"2023-05-13T21:12:56.152-06:00"},"s":"I",  "c":"NETWORK",  "id":51800,   "ctx":"conn29","msg":"client metadata","attr":{"remote":"127.0.0.1:53075","client":"conn29","doc":{"driver":{"name":"nodejs|Mongoose","version":"5.3.0|7.1.1"},"platform":"Node.js v16.17.1, LE","os":{"name":"win32","architecture":"x64","version":"10.0.19045","type":"Windows_NT"}}}}
{"t":{"$date":"2023-05-13T21:13:06.654-06:00"},"s":"I",  "c":"NETWORK",  "id":22943,   "ctx":"listener","msg":"Connection accepted","attr":{"remote":"127.0.0.1:53096","uuid":"9611eab4-7a75-49a0-9b44-d644599fe37c","connectionId":30,"connectionCount":18}}
{"t":{"$date":"2023-05-13T21:13:06.656-06:00"},"s":"I",  "c":"NETWORK",  "id":51800,   "ctx":"conn30","msg":"client metadata","attr":{"remote":"127.0.0.1:53096","client":"conn30","doc":{"driver":{"name":"nodejs|Mongoose","version":"5.3.0|7.1.1"},"platform":"Node.js v16.17.1, LE","os":{"name":"win32","architecture":"x64","version":"10.0.19045","type":"Windows_NT"}}}}

应用控制台输出

Connected to database 'inventory'
Server is listening on port 3000

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 02:17:22