I tried to connect my mongo cluster with my local server but this error keeps on showing up. I am following a tutorial and it seems to work fine for the tutor but this error comes for me. I have provided the error screenshot below.
The src has been provided
const express = require('express');
const env = require('dotenv');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
//routes
const userRoutes = require('./routes/user');
//constants
env.config();
//mongodb connect
//mongodb+srv://root:<password>@cluster0.9ylhh.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
mongoose.connect(
`mongodb+srv://${process.env.MONGO_DB_USER}:${process.env.MONGO_DB_PASSWORD}@cluster0.9ylhh.mongodb.net/${process.env.MONGO_DB_DATABASE}?retryWrites=true&w=majority`,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
}
).then(() => {
console.log('Database connected');
});
//middleware
app.use(express.urlencoded({ extended: true}));
app.use(express.json());
app.listen(process.env.PORT, () => {
console.log(`server is running on port ${process.env.PORT}`);
});
I also did create a .env file with the credentials details and stuff
I tried to make a comment instead of an answer, but I don't have enough reputation.
If the error is authentication, maybe you have a problem with your credentials.
Does your username or password have any of these chars? : / ? # [ ] @
If they do, you'll have to URI encode them like so:
${encodeURIComponent(process.env.MONGO_DB_USER)}
${encodeURIComponent(process.env.MONGO_DB_PASSWORD)}
More info here: https://docs.mongodb.com/manual/reference/connection-string/#examples
BTW: You forgot the env part on your ${process.MONGO_DB_PASSWORD}.