0

I'm trying to connect to a MongoDB cluster from VSCode, in the connection string I'm using the correct username and the password that I auto-generated for the database user. I've also tried adding my current IP to the IP whitelist as well the access from anywhere global IP option. The error I got before this one read something like the IP address needs to be added to the IP whitelist.

This is the server configuration:

const express = require('express');
const { json } = require('express');
const authRoutes = require('./routes/auth');
const cors = require('cors');
const morgan = require('morgan');
const mongoose = require('mongoose');
const dotenv = require('dotenv');


dotenv.config();
const app = express();
app.use(express.json()); //alternative to body-parser

// connect to db
mongoose.connect(process.env.DATABASE, {
    useNewUrlParser: true,
    useFindAndModify: false,
    useUnifiedTopology: true,
    useCreateIndex: true
})
    .then(() => console.log('DB connected'))
    .catch(err => console.log('DB connection ERROR: ', err));


// morgan allows us to get server side feedback for each router/request.
app.use(morgan('dev'));

// use cors module to define accepted request sources 
if (process.env.NODE_ENV = 'development') {
    app.use(cors({ origin: `http://localhost:3000` }))
}


// middleware
app.use('/api', authRoutes);


const port = process.env.PORT
app.listen(port, () => console.log(`Server listening on port ${port} - ${process.env.NODE_ENV}`));


Jaiylon
  • 67
  • 6

1 Answers1

-1

Few things to verify:

  • Format of the username and/or password in process.env.DATABASE variable should not be using the brackets (< or >)

Sample DB string mongodb+srv://<username>:<password>@cluster.mongodb.net/<databasename>?retryWrites=true

Updated DB string mongodb+srv://appuser:apppassword@cluster.mongodb.net/testdb?retryWrites=true

  • Use the database user and password to login and not the Atlas account credentials

  • White list the IP address in Atlas (seems you have already done that)

Here is an article outlining steps to connect to Mongo Atlas using Node

Bharat
  • 74
  • 3