MongoNotConnectedError:必须连接MongoClient才能执行此操作.如何处理此错误



cmd

我该怎么解决这个问题。只是显示MongoClient必须连接才能执行此操作

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)

只需注释代码或删除client.close((

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

当我正在努力解决这个问题时,作者提到的想法是,如果你的密码包含某些字符,你必须将它们更改为基于百分比的代码:如果用户名或密码包含以下字符:

:/?#[]@

这些字符必须使用百分比编码进行转换。https://www.mongodb.com/docs/manual/reference/connection-string/

我遇到了同样的问题,我将方法更改为await和async,并在操作中添加了await。因此操作将完成,然后连接将关闭

我需要将数据库密码中的@替换为%40

最新更新