'Why is my process.env not working properly?
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
