1

I am practicing MongoDB, which requires you to connect your terminal to MongoDB Atlas using a connection string. I am storing the credential parts of my connection string in .env file but it shows authentication error when I do that.

import express from "express";
import Cors from "cors";
import mongoose from "mongoose";
import dotenv from "dotenv";

dotenv.config();
const app = express(); 
const port = process.env.PORT;
const connection_url = `mongodb+srv://${process.env.USERNAME}:${process.env.PASSSWORD}@clustername.eksth.mongodb.net/testdatabase?retryWrites=true&w=majority`;

app.use(express.json());
app.use(Cors());

mongoose.connect(connection_url, {
  useNewUrlParser: true
});
mongoose.connection.on("error", function (error) {
  console.log(error);
});
mongoose.connection.on("open", function () {
  console.log("Connected to MongoDB Database");
});

app.get("/", (req, res) => res.status(200).send("hi"));

app.listen(port, () => console.log(`Listening on localhost:${port}`));

The process.env.PORT works perfectly fine but not the string.

Error I am getting:

MongoServerError: bad auth : Authentication failed.
3
  • 2
    Watch out of the typo in PASSSWORD (there are 3 'S') Commented Mar 12, 2022 at 9:11
  • 2
    you can simply save the complete url in environment file mongodb+srv://user:[email protected]/dbname Commented Mar 13, 2022 at 7:49
  • this did the job for me
    – Tichel
    Commented Jan 2, 2023 at 10:36

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.