skip to Main Content
const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/fruitsDB", {useNewUrlParser: true});

const fruitSchema = new mongoose.Schema ({
  name: String,
  rating: Number,
  review: String
});

const Fruit = mongoose.model("Fruit", fruitSchema);

Fruit.find((err, fruits) => {
  if (err) {
    console.log(err);
  } else {
    fruits.forEach((fruit) => console.log(fruit.name));
  };

  mongoose.connection.close(function() { process.exit(0); });
});

In the above code mongoose.connection.close(function() { process.exit(0); });, works but mongoose.connection.close(),or mongoose.disconnect(); dosen’nt work. What do I need to do to make it work? Or suggest some other cleaner way to close connection.

My dependencies are: "dependencies": { "mongodb": "4.10", "mongoose": "^6.6.6" }

2

Answers


  1. Chosen as BEST ANSWER

    I asked this question when I just started with mongoDB, and I realized that most of the time I don't really need the connection to be closed. That it should connect at the start of the application and keep it open.

    From what I observed, .disconnect() function itself takes some time to get executed. So you can leave it be, setting the a time out doesn't help if you want the connection to disconnect immediately, because even after the function is triggered after the set time, disconnect() itself takes some time to disconnect.

    For some reasons mongoose.connection.close(function() { process.exit(0); });, did instantly close the connection for me though.


  2. as said here this is a timing issue.
    you can fix it as follows:

    setTimeout( () => {
      mongoose.disconnect()
    }, 1000)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search