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

158
Views
MongoBulkWriteError: Cannot use a session that has ended. Can't add new documents to the database

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

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!