简体   繁体   中英

How and where properly connect and end mongoDB connection in nodejs

Hi guys i have this pice of code ( https://github.com/MrRav3n/Angular-Marketplace/blob/master/server.js ) and i wonder if i correctly stard and end my database connection. Do i have to connect and end db connection in every app.route or is it correct to start database connection and end it at the end of the file?

Pls check my code and give me feedback.

Thanks in advance!

mongoose
.connect(
"mongodb+srv://MrRav3n:DAW100kr@cluster0-6xfty.mongodb.net/test?retryWrites=true&w=majority"
.then(result => {
app.listen(3000);
.catch(err => console.log(err));

I recommend you install this package "moongose" a put the code above at the end of your code. source: Udemy Course "NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)"

I don't think there is any need to connect multiple times to your database. In fact one could put all the routes that depend on the database into the callback of the connect.

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