Home > front end >  mongoose not connected to database
mongoose not connected to database

Time:10-11

why i should commmented the code

 await mongoose.connection.close()

to make it work ?

here is my code:

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

CodePudding user response:

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);
}

CodePudding user response:

You see the function 'main' is asynchronous, all those async functions are called asynchronously. You can try calling it with .then and do everything else in that .then:

... All the previous code 
main().then(()=> {
  async function createListing() {
  ...
  // All the other code
})

CodePudding user response:

Please comment on this line await mongoose.connection.close() then try I hope work it perfectly!!

  • Related