javascript - MongoError : Topology is closed, 请连接(client.close 和 client.connect 问题)

标签 javascript node.js database mongodb mongodb-atlas

( Node :21140)UnhandledPromiseRejectionWarning:MongoError:拓扑已关闭,请连接

我认为这是一个与 CRUD 操作的每个函数中重复 client.connect 和 client.close 相关的错误,如下代码所示

//我认为集群 uri 没有问题,所以我没有发布它,因为它连接正常

const MongoClient = require("mongodb").MongoClient;

const uri = "mongodb+srv://username:pasword@some cluster"; 
//I think there is no issue with cluster uri so I didn't post that since it connects fine


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



async function AddnewService(service) {
    await client.connect()
    const database = client.db("twitch")
   const usr = await database.collection("recipes").find({ Title: service.Title }).toArray()
    if (usr.length >= 1) {
        await client.close()
        return { message: "Title already in use" }
    }
    else {
        const result = await database.collection("recipes").insertOne(service)
        await client.close()
        return { message: "Service Added to Database" }
    }
}

async function FetchAllserviceSearch(service) {
    await client.connect()
    const database = client.db("twitch")
    let recipesCursor = await database.collection("recipes").find({})
    while (await recipesCursor.hasNext()) {                       //make sure to put await on cursor .hasnext()
        let recipe = await recipesCursor.next()
        console.log(recipe)
    }
    await client.close()

    return { message: "User Added to Database" }
}


module.exports = {
    AddnewService,
    FetchAllserviceSearch
}

我尝试分配让 client.connect 和 client.close 仅​​被调用一次,但总是会导致新的错误。 我无法消除 module.export 因为我需要它们在其他文件中使用。

所以我需要一些帮助来解决这个问题,而不需要不必要的重复,因为 mongodbAtlas 会导致问题。

最佳答案

不要关闭你的数据库连接,你处于竞争状态,当两个请求到来时,一个将关闭另一个将打开。

client.close(); -----> remove

对所有请求使用相同的数据库连接。

const uri = "mongodb+srv://username:<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7909180a0e160b1d391a150c0a0d1c0b4957101248090c571416171e161d1b57171c0d" rel="noreferrer noopener nofollow">[email protected]</a>/myFirstDatabase?retryWrites=true&w=majority";

let con;

async function connect(service) {
   if (con) return con; // return connection if already conncted
   const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
   con = client.connect()
   return con;
}


async function AddnewService(service) {
    const client = await connect();
    const database = client.db("twitch")
    const usr = await database.collection("recipes").find({ Title: service.Title }).toArray()
    if (usr.length >= 1) {
        // await client.close(); -----> remove
        return { message: "Title already in use" }
    }
    else {
        const result = await database.collection("recipes").insertOne(service)
        return { message: "Service Added to Database" }
    }
}

async function FetchAllserviceSearch(service) {
    const client = await connect();
    const database = client.db("twitch")
    let recipesCursor = await database.collection("recipes").find({})
    while (await recipesCursor.hasNext()) {                       //make sure to put await on cursor .hasnext()
        let recipe = await recipesCursor.next()
        console.log(recipe)
    }
    // await client.close(); -----> remove
    return { message: "User Added to Database" }
}


module.exports = {
    AddnewService,
    FetchAllserviceSearch
}

关于javascript - MongoError : Topology is closed, 请连接(client.close 和 client.connect 问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66865958/

相关文章:

javascript - 在 Razor 中将小数字段显示为 Int

node.js - Firebase Firestore 函数从通配符获取数据,然后将数据写入另一个集合

node.js - Phusion Passenger 和 Node.js

node.js - 我如何为 npm 安装计时?

ruby-on-rails - 在学习 Ruby On Rails 教程之后,无法将用户添加到数据库

javascript - 图像而不是单选按钮/文本?

javascript - 为什么舍入 -0.1 返回 -0

javascript - 如何在鼠标悬停在栏上时显示标签

php - 如何使用密码从 MS Access 数据库中检索网页数据

php - 收件箱/消息数据模型