I'm new to mongodb/mongoose and javascript. When I try to use mongoose.disconnect, it throws an error
return new error_1.MongoNetworkError('connection establishment was cancelled'); ^ MongoNetworkError: connection establishment was cancelled "
below is the code snippet -
const mongoose = require("mongoose");
const mongoDB = "mongodb://127.0.0.1:27017/fruitsDB";
mongoose
.connect(mongoDB,{
useNewUrlParser:true,useUnifiedTopology:true
})
.then(() => console.log("MongoDB connected"))
.catch((err) => console.error("error!!! - ",err));
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:"pretty solid as a fruit"
});
// fruit.save();
const personSchema = new mongoose.Schema ({
name:String,
age:Number
});
const Person = mongoose.model("Person",personSchema);
const person = new Person ({
name:"xyz",
age:37
});
person.save();
const kiwi = new Fruit({
name:"Kiwi",
score:10,
review:"The best fruit"
});
const orange = new Fruit({
name:"Orange",
score:4,
review:"Too sour for me"
});
const banana = new Fruit({
name:"Banana",
score:10,
review:"Weird texture"
});
// Fruit
// .insertMany([kiwi,orange,banana])
// .then( ()=> console.log("Succesfully saved all the fruits to fruitsDB"))
// .catch( (err) => console.log(err));
async function getFruits() {
const fruit = await Fruit.find({});
mongoose.disconnect();
return fruit;
}
const printFruitsName = async () => {
const res = await getFruits();
res.forEach((fruit) => console.log(fruit.name));
}
printFruitsName();
Please assist!
tldr: Attempted to close MongoDB using mongoose.disconnect() but encountered an error stating that the connection was not established
Is there a way to properly close the mongoose database connection?