user609511
user609511

Reputation: 4261

mongoose not connected to database

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:

Upvotes: 0

Views: 33

Answers (3)

shahzaib ghumman
shahzaib ghumman

Reputation: 21

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

Upvotes: 1

Nabed Khan
Nabed Khan

Reputation: 30

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

Upvotes: -1

Fabian Strathaus
Fabian Strathaus

Reputation: 3570

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

Upvotes: 1

Related Questions