Node js code exit point

The following code runs fine. data gets inserted into the collection. However, the program doesnoot exit. The console just stays there. How to exit gracefully?

const mongoClient = require('mongodb').MongoClient
const url = 'mongodb://localhost:27017'
const schema = 'learndb'

const client = new mongoClient(url,{ useUnifiedTopology: true })

const connection = client.connect(function(err,client){
        console.log('~~~UNABLE TO CONNECT TO MONGO~~~')
        throw err
    console.log('~~~SUCCESSFULLY CONNECTED TO MONGO~~~')

const db = client.db(schema)

db.collection('mycol').insertMany ([

Hey @halwaraj when you post code in the forum, you need to format it. To do so you can either select all the code and click the </> button, or type 3 backticks ``` on a separate line both before and after the code block.

I have done it for you this time.

No so sure about process.exit(), that the program does not exit normally means there’s still something going on in the background… @halwaraj I haven’t tried it myself, but what if you just close() the client?

OOps… i usually do that…missed it somehow… will remember next time…

1 Like

No… it has finished processing…

yes close will exit the program but also closes the DB connection. which is a performance issue… so is there a way to acheive this???

i’m… confused.

How is it a performance issue if your entire program is running a single query?

Having lingering connections to the database would be a performance issue… running infinitely many queries would be a performance issue… disconnecting from the database would not.

1 Like

i mean connection pool.
It would help to re use the connection for every new request instead of creating a new connection everytime.

Well there are no requests in the code you posted, it looks more like a CLI script of sorts. If you have a server running handling requests, you can of course reuse the same connection as your server (hopefully) would’t terminate by itself anyway.