Node.js使用insertOne()时遭遇PoolClosedError错误求助
解决MongoDB PoolClosedError:Attempted to check out a connection from closed connection pool
问题原因
你的代码中createListing是异步函数,但在main函数的try块中调用时未添加await关键字。这会导致createListing内部的插入操作还未完成,finally块就执行了client.close(),提前关闭了MongoDB连接池。当后续插入操作尝试从已关闭的连接池获取连接时,就会抛出PoolClosedError。
修复方案
在调用createListing时添加await,确保插入操作完成后再关闭客户端连接:
修正后的完整代码
const { MongoClient } = require('mongodb'); async function main(){ const uri = "mongodb+srv://netTheCoder:welcome@cluster0.ra2eh5p.mongodb.net/?retryWrites=true&w=majority"; const client = new MongoClient(uri); try{ await client.connect(); // 添加await等待异步操作完成 await createListing(client,{ name: "Hello Tower", summary: "A buitiful mesmarising building in Switzerland", bedroom: 30, bathrooms: 28 }) } catch(e){ console.log(e); }finally{ await client.close(); } } async function createListing(client,newListing){ const result = await client.db("SampleDatabase").collection("Names").insertOne(newListing); console.log(result); } main().catch(console.error);
说明
添加await后,代码会等待createListing中的insertOne操作完全执行完毕,才会进入finally块关闭客户端连接,避免了连接池提前关闭导致的错误。
内容的提问来源于stack exchange,提问作者98k374
相关产品推荐
相关产品推荐

