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){
if(err){
console.log('~~~UNABLE TO CONNECT TO MONGO~~~')
throw err
}
console.log('~~~SUCCESSFULLY CONNECTED TO MONGO~~~')
})
const db = client.db(schema)
db.collection('mycol').insertMany ([
{id:'1101',value:'ddddddddd'},
{id:'1102',value:'aaaaaaaaa'},
{id:'1103',value:'bbbbbbbbb'},
{id:'1104',value:'ccccccccc'},
])
[off-topic]
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.
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?
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.
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.