Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

361
Views
mongoose.connection.close() or mongoose.disconnect() takes ~10-12 seconds before the connection actually closes
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);

const fruit = new Fruit({
  name: "Apple",
  rating: 7,
  review: "Good Fruit"
});
fruit.save();

const banana = new Fruit({
  name: "banana",
  rating: 9,
  review: "Noice"
});

const mango = new Fruit({
  name: "Mango",
  rating: 10,
  review: "best Fruit"
});

Fruit.insertMany([banana, mango], function (err) {
  if (err) console.log(err);
  else console.log("Inserted all!");
});

Fruit.find(function (err, fruits) {
  if (err) console.log(err);
  else {
    mongoose.connection.close();
    fruits.forEach((fruitdata) => {
      console.log(fruitdata.name);
    });
  }
});

The mongoose.connection.close() takes almost 10-12 seconds to before the connection actually closes. I have also tried mongoose.disconnect() but the problem still persists. Using the async function and await key also made no differnce. I don't know what is going wrong. But from my understanding in the following snippet the error handling is taking time.

Fruit.find(function (err, fruits) {
  if (err) console.log(err);
  else {
    mongoose.connection.close();
    fruits.forEach((fruitdata) => {
      console.log(fruitdata.name);
    });
  }
});

If i just place the mongoose.connection.close() or mongoose.disconnect() above this snippet, the connection is closed in milli secs but when placed inside the .find's callback function it takes 10-12 seconds.

about 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!