Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

mongoose not connected to database

why i should commmented the code

 await mongoose.connection.close()

to make it work ?

here is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const { MongoClient } = require("mongodb");
const mongoose = require('mongoose');
require('dotenv').config();

async function main() {
 
   const uri = process.env.MONGO_URL;
 
  try {
    // Connect to the MongoDB cluster   
    await mongoose.connect(uri)
    .then(()=> console.log("connect Succes"))
    .catch((err) => {console.error(err)});

    await createListing();

  } finally {
    // Close the connection to the MongoDB cluster
    await mongoose.connection.close()
    console.log("connect Closed") 
  }
}

main().catch(console.error);


async function createListing() { 

  const piscSchema = new mongoose.Schema({
    name: String,
    date: { type: Date, default: Date.now },
    pool: String,
    point: Number,
    isAdd:Boolean
  });

  const piscModel = mongoose.model('piscModel', piscSchema,  'PointPiscine');

  var itemPisc = new piscModel({  
    date:"12.10.2022",
    pool:"dsfs",
    point: 70,
    isAdd:false 
  });

 
  itemPisc.save(function (err, res) {
      if (err) console.error(err);
      console.log(res)
    });

    console.log("fin function call")


}

when i am not commented the code that close the connection.
i got this message enter image description here

it is strange because it is connected to my mongodb.

as you can see the console log:

  • connect Succes
  • fin function call
  • connect Closed

>Solution :

You are calling the following function using a callback

itemPisc.save(function (err, res) {
  if (err) console.error(err);
  console.log(res)
});

This way the code continues to run without waiting for the result of this operation. It will then close the database connection without waiting for the result of this save function, which leads to this error.

If you modify you function the following way, it should wait for the result and close the connection afterwards:

try {
  console.log(await itemPisc.save());
} catch (err) {
  console.log(err);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading