简体   繁体   中英

when to close connection in mongodb?

i use node js express, mongodb for API and mongoClient for connection. i fetch data it works fine ,and i try without refreshing it trows error that " Topology is closed"

 const express=require("express") const router=express.Router() // const bodyParser =require("body-parser") const client=require("./client") // express.use(bodyParser.json()); // express.use(bodyParser.urlencoded({ extended: true })); router.get("/users", async(req,res)=>{ console.log("rouete 3") try{ client.connect() var db= await client.db("mydb") var collection= await db.collection("myDataCol") var cvb= await collection.find().toArray() res.json(cvb) console.log(cvb) } catch(er){ console.log(`SOMETHINGS WENT WRONG: ${er}`) res.json({"scas":er})} finally{ client.close(()=>{console.log("closed")}) } }) module.exports=router
 <html> <head> <title>form</title> </head> <body> <h2>New User</h2> <hr/> <!-- <form action="/user" method="POST"> <input type="text" name="name"> <input type="text" name="lastName"> <input type="submit"> </form> <hr> <form action="/user/delete" method="POST"> <input type="text" name="name" > <input type="text" name="lastName"> <input type="submit"> </form> --> <hr> <form action="/users" method="GET"> <input type="submit"> </form> </body> </html>

enter image description here , when i disable client.close() it works again and fetch data every time when i click to to the bottom to get

Don't connect to mongo client in your routes, connect in your index or start file and pass it from there. DB connection should be open throughout whole application, from start to end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM