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

MongoDB本地数据存储失败:PoolClosedError问题求助

问题原因

你遇到的PoolClosedError核心原因是调用异步函数createListingbases时未加await:

  • createListingbases是异步函数,不加await调用会立即返回Promise,不会等待数据库插入操作完成
  • 主线程会直接进入finally块执行client.close(),提前关闭了MongoDB连接池
  • 此时createListingbases内的insertOne操作仍在执行,尝试从已关闭的连接池获取连接,触发该错误

另外,代码中导入的mongoose相关模块(Collection、connection)未实际使用,属于冗余代码,可直接移除。

修复方案
  1. 在main函数中调用createListingbases时添加await,确保数据库操作完成后再关闭连接
  2. 移除无用的mongoose导入语句
  3. 确认本地MongoDB服务已启动(可通过mongod命令或系统服务管理工具检查)
修正后的代码
const { MongoClient } = require('mongodb');

async function main(){
    const url = "mongodb://127.0.0.1:27017/mydb"
    const client = new MongoClient(url);
    
    try{
        await client.connect();
        console.log('connection connected..')
        // 关键修改:添加await等待异步操作完成
        await createListingbases(client,{
            name: "vikram is best",
            summmary : "just another day of coding",
            bedroom: "yes i am single",
            bathrooom: "no comments :|"
        })
    } catch(e){
        console.error(e);
    } finally {
        await client.close()
    }
}

main().catch(console.error)

async function createListingbases(client,newListing){
    const result = await client.db("sample_ddb").collection("listing and reviews").insertOne(newListing)
    console.log(`new listing created with the following id : ${result.insertedId}`);
}
额外检查点
  • 确认本地MongoDB服务运行在127.0.0.1:27017端口
  • 若指定的数据库sample_ddb或集合listing and reviews不存在,MongoDB会自动创建,无需手动提前创建

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 02:57:39