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.