我正在尝试连接mongodb。它显示我MongoServerError:bad auth:验证失败。代码如下
const express = require("express");
const cors = require("cors");
const { MongoClient } = require("mongodb");
require("dotenv").config();
const port = process.env.PORT || 4000;
const app = express();
app.use(cors());
app.use(express.json());
//mongodb connect
const uri = `mongodb+srv://${process.env.DATABASE_USER}:${process.env.DATABASE_PASS}@cluster0.zobm7.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
client.connect((err) => {
const collection = client.db("mac-yard").collection("products");
// perform actions on the collection object
console.log("database conected");
client.close();
});
app.get("/", (req, res) => {
res.send("hello");
});
app.listen(port, () => {
console.log("listening to port", +port);
});
3条答案
按热度按时间vlju58qv1#
I just encountered this error:
Server is running on port: 5000 MongoServerError: bad auth : Authentication failed. at Connection.onMessage (/home/mostafa/documents/local-repositories/mern-mongodb-tutorial/server/node_modules/mongodb/lib/cmap/connection.js:202:30) at MessageStream. (/home/mostafa/documents/local-repositories/mern-mongodb-tutorial/server/node_modules/mongodb/lib/cmap/connection.js:62:60) at MessageStream.emit (node:events:527:28) at processIncomingData (/home/mostafa/documents/local-repositories/mern-mongodb-tutorial/server/node_modules/mongodb/lib/cmap/message_stream.js:108:16) at MessageStream._write (/home/mostafa/documents/local-repositories/mern-mongodb-tutorial/server/node_modules/mongodb/lib/cmap/message_stream.js:28:9) at writeOrBuffer (node:internal/streams/writable:390:12) at _write (node:internal/streams/writable:331:10) at Writable.write (node:internal/streams/writable:335:10) at TLSSocket.ondata (node:internal/streams/readable:766:22) at TLSSocket.emit (node:events:527:28) { ok: 0, code: 8000, codeName: 'AtlasError', [Symbol(errorLabels)]: Set(1) { 'HandshakeError' } **Solution:**If you've got a config.env file in your project server side directories, where you have put your
ATLAS_URI
Just login to your https://cloud.mongodb.com account and beside your Cluster name, you would find a green button namedConnect
, there, click onConnect your application
and copy the connection string. Go back to the config.env file and update the ATLAS_URI like below:ATLAS_URI=mongodb+srv://<username>:<password>@sandbox.jadwj.mongodb.net/employees?retryWrites=true&w=majority
Now I think you are good to go 😉pzfprimi2#
对于我的情况,用户ID密码是正确的。但我的错误是“〈〉”
mongodb+服务器://用户:@cluster0
解决方案〉〉〉没有标记mongodb+srv://用户:密码@cluster0
ih99xse13#
你可能已经尝试过了,但是我用最基本的登录凭据创建了一个新用户,这阻止了我得到这个错误。请参见https://www.youtube.com/watch?v=wvlJGvP18Qk支持的链接。
从那里你可以尝试用你想要的详细信息创建一个用户。