When to close MongoDB database connection in Nodejs

前端 未结 8 624
一整个雨季
一整个雨季 2020-11-28 21:56

Working with Nodejs and MongoDB through Node MongoDB native driver. Need to retrieve some documents, and make modification, then save them right back. This is an example:

8条回答
  •  离开以前
    2020-11-28 22:17

    Here an extended example to the answer given by pkopac, since I had to figure out the rest of the details:

    const client = new MongoClient(uri);
    (async () => await client.connect())();
    
    // use client to work with db
    const find = async (dbName, collectionName) => {
      try {
        const collection = client.db(dbName).collection(collectionName);
        const result = await collection.find().toArray()
        return result;
      } catch (err) {
        console.error(err);
      }
    }
    
    const cleanup = (event) => { // SIGINT is sent for example when you Ctrl+C a running process from the command line.
      client.close(); // Close MongodDB Connection when Process ends
      process.exit(); // Exit with default success-code '0'.
    }
    
    process.on('SIGINT', cleanup);
    process.on('SIGTERM', cleanup);
    

    Here is a link to the difference between SIGINT and SIGTERM. I had to add the process.exit(), otherwise my node web-server didn't exit cleanly when doing Ctrl + C on the running process in command line.

提交回复
热议问题