(node:21140) UnhandledPromiseRejectionWarning: MongoError: Topology is closed, please connect
I think it is an error relating to repetition of client.connect and client.close in each function of CRUD operation as shown in code below
//I think there is no issue with cluster uri so I didn't post that since it connects fine
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
}
I tried allot to make that client.connect and client.close be called only once but there have always be a new error caused by it. I cannot eliminate module.export cause I need them for usage in other file.
So I need a little help to make it work out some how without that needless repetition as mongodbAtlas causes issues with that.