mongodb MongoServerClosedError:服务器已关闭

amrnrhlw  于 2023-08-04  发布在  Go
关注(0)|答案(1)|浏览(184)

我试图连接到我的MongoDB数据库,并返回一个数组,其中包含集合“myCollection”中的每个文档(json)。下面是一个例子:

const uri = "uri"; // Can't post real uri here
const client = new MongoDB.MongoClient(uri);

app.get("/api", (request, response) => {
    async function getData() {
        let result = [];
        try {
            await client.connect();
    
            const db = client.db("myDatabase");
            const collection = db.collection("myCollection");
            const cursor = collection.find({});
            for await (const item of cursor) {
                result.push(item);
            }
        }
        catch (e) {
            console.log(e);
        }
        finally {
            await client.close();
        }
        return result;
    };
    response.send(getData());
});

字符串
问题是它返回以下错误:

MongoServerClosedError: Server is closed
    at Server.command (myPath\node_modules\mongodb\lib\sdam\server.js:157:22)
    at FindOperation.executeCallback (myPath\node_modules\mongodb\lib\operations\find.js:30:16)
    at myPath\node_modules\mongodb\lib\operations\operation.js:65:18
    at node:internal/util:411:7
    at new Promise (<anonymous>)
    at node:internal/util:397:12
    at FindOperation.execute (myPath\node_modules\mongodb\lib\operations\operation.js:66:11)   
    at retryOperation (myPath\node_modules\mongodb\lib\operations\execute_operation.js:152:32) 
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async executeOperationAsync (myPath\node_modules\mongodb\lib\operations\execute_operation.js:107:20) {
  [Symbol(errorLabels)]: Set(0) {}
}


其中myPath是包含我的项目文件的文件夹。通过测试,我发现如果删除for await...of循环,错误就会消失。

m528fe3b

m528fe3b1#

在代码中,使用response.send(getData()),其中getData()是一个异步函数。此时异步操作尚未完成。实际发生的是向客户端发送Promise(而不是结果)。同时,Node.js继续执行事件循环。这可能会导致mongodb在所有异步操作完成之前关闭。所以,一个简单的解决方案:

app.get("/api", async (request, response) => { //add async
    async function getData() {
        let result = [];
        try {
            await client.connect();
    
            const db = client.db("myDatabase");
            const collection = db.collection("myCollection");
            const cursor = collection.find({});
            for await (const item of cursor) {
                result.push(item);
            }
        }
        catch (e) {
            console.log(e);
        }
        finally {
            await client.close();
        }
        return result;
    };
    const data = await getData(); //add this
    response.send(data);
});

字符串
顺便说一下,你不应该在请求中连接和关闭你的mongodb连接。你应该在全球范围内做的事情。

相关问题