I am trying to add new documents to the database but every time it is throwing this error: MongoBulkWriteError: Cannot use a session that has ended
Here is my code-
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/fruitsDB", {
useNewUrlParser: true,
});
const fruitSchema = new mongoose.Schema({
name: String,
rating: {
type: Number,
min: 1,
max: 10,
},
review: String,
});
const Fruit = mongoose.model("Fruit", fruitSchema);
const kiwi = new Fruit({
name: "Kiwi",
rating: "10",
review: "The best fruit!",
});
const orange = new Fruit({
name: "Orange",
rating: 4,
review: "Too sour for me",
});
Fruit.insertMany([kiwi, orange], function (err) {
if (err) {
console.log(err);
} else {
console.log("Succesfully saved all the fruits to fruitsDB");
}
});
Fruit.find(function (err, fruits) {
if (err) {
console.log(err);
} else {
mongoose.connection.close();
fruits.forEach(function (fruit) {
console.log(fruit.name);
});
}
});
At first I added a few elements without using the connection.close() but after i added this connection close statement, it kept giving this error. I tried to move connection.close() to different places but nothing worked and i couldn't find anything online.
Please help Thank you in advance