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

点击客户端站点时Express服务抛出MongoDB非法状态转换错误如何解决

问题原因

错误触发的核心原因是同一个MongoClient实例出现了状态冲突:你在代码中调用了两次client.connect()方法,第一次回调执行完成后立刻调用client.close()将客户端状态置为关闭,后续run异步函数中再次尝试调用client.connect()连接已关闭的客户端,违反了MongoDB客户端的状态转换规则,直接抛出运行时错误。

解决方案
  • 首先删除冗余的早期测试连接代码,就是如下这段完全没必要的逻辑:
client.connect(err => {
    const collection = client.db("carMechanic").collection("services");
    // perform actions on the collection object
    client.close();
});
  • 调整Express服务启动时机,确保MongoDB连接建立成功后再监听端口,避免服务启动后数据库未就绪的异常。

修正后完整可运行代码

const express = require('express');
const { MongoClient } = require('mongodb');
const cors = require('cors');
require('dotenv').config()

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

// 中间件
app.use(cors());
app.use(express.json());

const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.84pml.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

async function run() {
    try {
        await client.connect();
        const database = client.db("carMechanic");
        const servicesCollection = database.collection("services");

        // POST接口
        app.post('/services', async (req, res) => {
            const service = req.body;
            const result = await servicesCollection.insertOne(service);
            console.log(result);
            res.send('post hitted')
        });

        // 数据库连接成功后再启动服务
        app.listen(port, () => {
            console.log(`服务运行在端口${port}`)
        });

    } catch (err) {
        console.dir(err)
    }
    // 服务运行期间不要关闭数据库连接,注释关闭逻辑
    // finally {
    //     await client.close();
    // }
}

run().catch(console.dir);

app.get('/', (req, res) => {
    res.send('Running Genius Server');
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:36:03