'MongoServerError: bad auth

I make an app using node.js. and connect this with MongoDB. But when I start my server it gives me an error. The error is below.

Example app listening on port 5000

MongoServerError: bad auth : Authentication failed.
at Connection.onMessage (C:\Taha\Project\Assignment\11.warehouse\server\node_modules\mongodb\lib\cmap\connection.js:203:30)
at MessageStream.<anonymous> (C:\Taha\Project\Assignment\11.warehouse\server\node_modules\mongodb\lib\cmap\connection.js:63:60)
at MessageStream.emit (node:events:390:28)
at processIncomingData (C:\Taha\Project\Assignment\11.warehouse\server\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
at MessageStream._write (C:\Taha\Project\Assignment\11.warehouse\server\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
at writeOrBuffer (node:internal/streams/writable:389:12)
at _write (node:internal/streams/writable:330:10)
at MessageStream.Writable.write (node:internal/streams/writable:334:10)
at TLSSocket.ondata (node:internal/streams/readable:754:22)
at TLSSocket.emit (node:events:390:28)


Solution 1:[1]

first: npm install dotenv

second: In server side index.js import and configure dotenv: require("dotenv").config();

third: in .env file, write the user name and password with a name for-ex( DB_USER=username DB_PASS=password )

forth: username and password title as ${process.env.DB_USER} and ${process.env.DB_PASS} have to used by replaced on uri codes 'username' .

now check the terminal and database Thank you

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mahfuz Rahman