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

Node连接MongoDB报MongoExpiredSessionError会话已结束错误如何解决

错误原因

你代码中调用toArray()时使用了回调函数写法,该操作是异步非阻塞的,外层代码不会等待回调执行完成,就会进入finally块执行await client.close()关闭数据库连接。等到回调实际触发执行时,数据库会话已经被销毁,就会抛出MongoExpiredSessionError: Cannot use a session that has ended错误。

解决方案

推荐统一使用async/await写法改写查询逻辑,保证所有数据库操作执行完成后再关闭连接,修正后代码如下:

const { MongoClient } = require('mongodb')
const url = "mongodb://localhost:27017"
const client = new MongoClient(url);

async function main(){
    const dbName = 'my-react-admin'
    try {
        await client.connect();
        console.log('Connect to database!')
        const db = client.db(dbName);
        // 改用await等待查询结果返回,替代回调写法
        const userList = await db.collection('users').find({}).toArray()
        console.log(userList)
    } catch (e) {
        console.error(e);
    } finally {
        await client.close();
    }
}
main().catch(console.error);

如果确实需要保留回调写法,需要将关闭连接的逻辑移入回调内部,避免提前断开连接:

// 回调写法示例,不推荐与外层async/await混用
async function main(){
    const dbName = 'my-react-admin'
    try {
        await client.connect();
        console.log('Connect to database!')
        const db = client.db(dbName);
        db.collection('users').find({}).toArray(async (err, data) => {
            if (err) throw err
            console.log(data)
            // 回调执行完成后再关闭连接
            await client.close()
        })
    } catch (e) {
        console.error(e);
    }
}
main().catch(console.error);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:36:04