Mehedi Hasan
Mehedi Hasan

Reputation: 149

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

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@[email protected]/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)

Upvotes: 12

Views: 23107

Answers (5)

Bahurtsev
Bahurtsev

Reputation: 1

I forgot to await before an async method when working with mongoose.

await doc.save();

Upvotes: 0

Michael Randazzo
Michael Randazzo

Reputation: 11

As I'm struggling with this, the author is referring to the idea that if your password contains certain characters, you must change them out for percent based codes: If the username or password includes the following characters:

: / ? # [ ] @

those characters must be converted using percent encoding. https://www.mongodb.com/docs/manual/reference/connection-string/

Upvotes: 1

Mehedi Hasan
Mehedi Hasan

Reputation: 149

I needed to replace @ with %40 in the database password

Upvotes: 0

Aran Tamool
Aran Tamool

Reputation: 309

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

Upvotes: 0

Hayeul Tanjib
Hayeul Tanjib

Reputation: 361

Just comment the code or remove client.close()

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

Upvotes: 30

Related Questions