MongoNotConnectedError: MongoClient must be connected to perform this operation. How to handle this error?

Viewed 4025

cmd How can i solve this. Just showing MongoClient must be connected to perform this operation at getTopology ..... at collection.insertOne .... at maybePromise..

const express = require('express');
const {MongoClient} = require('mongodb');
const password = 'NLJXkuGFhUd68@9';



const uri = "mongodb+srv://organicUser:NLJXkuGFhUd68@9@cluster0.px7rc.mongodb.net/organicdb? 

retryWrites=true&w=majority"; const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

const app = express();

app.get('/', (req, res) => {
    res.send("Hello, I am Working");
})



client.connect(err => {
  const collection = client.db("organicdb").collection("products");

  // perform actions on the collection object
  const product = {name: "Modhu", price: 120, quantity: 30};
  collection.insertOne(product)
  .then(result => {
      console.log("One product added");
  })
  console.log("database connected");

});


app.listen(8000)
3 Answers

Just comment the code or remove client.close()

 finally {
           // await client.close();
        }

Solved. Just replace @ with %40 of the password

I had the same issue and I have changed the method to be await and async, and I added await to the operation. So the operation will be finished then the connection will be close

Related