首页 > 解决方案 > 关闭 mongoDB 连接

问题描述

服务器没有关闭连接,我找不到错误。

当我第一次访问服务器(本地主机)时,它会返回正确的结果。

但是下一次,它会发送警告,例如

[MONGODB DRIVER] 警告:不支持选项 [caseTranslate]

还有更多。然后它返回“错误”

async function report(prodNum) {
    try{
        await client.connect();
        let res = await findOneByprodNum(client, prodNum);
        return res;
    } catch (e){
        return "Error";
    } finally {
        client.close();
    }
}

async function findOneByprodNum(client, prodOfListing) {
    const result = await client.db("mobileContents").collection("food").findOne({
        prodNum: prodOfListing
    });
    if (result) {
        console.log(`Found Name, in: ${prodOfListing}`);
        console.log(result);
        return result;
    } else {
        console.log(`No listings found, in: ${prodOfListing}`);
        return null;
    }
}

客户 =

const client = new MongoClient(uri, {
    useUnifiedTopology: true,
    useNewUrlParser: true,
    connectTimeoutMS: 30000
});

标签: node.jsmongodb

解决方案


mongodb JS 驱动程序不是为关闭/重新连接而设计的

在应用启动时连接一次并共享client. 退出节点进程时关闭。

const client = new MongoClient(uri, {
    useUnifiedTopology: true,
    useNewUrlParser: true,
    connectTimeoutMS: 30000
});

async function startup(){
    await client.connect()
}

async function shutdown(){
    await client.close()
}

async function report(prodNum) {
    try{
        let res = await findOneByprodNum(client, prodNum);
        return res;
    } catch (e){
        console.error(e)
        return "Error";
    }
}

推荐阅读