简体   繁体   中英

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

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM