Tuesday, 23 October 2018

Should I close my mongoose node.js connection after saving into database?

I have the following code in my app.js which runs on server start (npm start)

mongo.mongoConnect('connection_string', 'users').then((x) => {
        console.log('Database connection successful');
        app.listen(5000, () => console.log('Server started on port 5000'));
    })
    .catch(err => {
        console.error(err.stack);
        process.exit(1);
    });


process.on('SIGINT', mongo.mongoDisconnect).on('SIGTERM', mongo.mongoDisconnect);

As you can see I open up SIGINT and SIGTERM for closing my connections upon process.exit

I've been reading a lot about how to deal with database connections in mongo and know that I should just invoke it once and have it across my application.

Does that mean that even after save() method when saving data to mongo followed by POST request, I should not be closing my connection? If I close it, how am I going to invoke it again since the connections happens on app start?

I'm asking it since in PHP I had the practice to always open and close my connection after querying MySql database.

Likewise, does it mean that the connection will close only on server shutdown in other words it will always be present since I do not want to shut down my node.js backend instance?



from Should I close my mongoose node.js connection after saving into database?

No comments:

Post a Comment