简体   繁体   中英

How to close mongodb connection using mongoose

Hi can anyone give me the right way to close mongodb connection using mongoose. I've tried to check many resources, but couldn't find the thing that I'm looking for. I don't understand when is the time to close it. Can anyone give the full example for it.

Is it like this?

const mongoose = require("mongoose");

module.exports = () => {
   mongoose.connect(process.env.MONGODB_URI);

mongoose.connection.on("error", (err) => {
   console.log(err, "ERROR");
   process.exit(1);
});
// disconnect here?
mongoose.disconnect()
};

or is like this after every query then close?

  const mongoose = require("mongoose");

  static async getBestSellingProducts(cb) {
      try {
        let results = await ProductModel.find(
          {
            stock: { $gte: 1 },
            sold: { $gt: 0 },
          },
           "dbId name photoURL sold",
         {
           sort: { sold: -1 },
           limit: 9,
         }
         ).exec();

         cb(null, results);
         // disocnnect here?
         mongoose.disconnect();
      } catch (err) {
            cb(err, null);
            // disconnect here
            mongoose.disconnect();
            }
         }

You shouldn't close the connection after every request if you want your program to do any requests afterwards. It does make sense to close it when your program stops, even though you don't technically have to do it.

process.on('exit', function (){
    mongoose.disconnect();
});

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