Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

288
Vistas
MongoDB authentication not working due to dotenv

I am trying to load the following from the .env file to index.js for MongoDB authentication.

DB_USER:(my user name here)
DB_PASS:(my password here)

I have checked and there are apparently no issues with the user name and password.

I have also added require('dotenv').config(); and process.env.DB_USER, process.env.DB_PASS to my index.js.

const express = require('express');
const cors = require('cors');
const { MongoClient, ServerApiVersion } = require('mongodb');
require('dotenv').config();
const port = process.env.PORT || 5000;
const app = express();

// middleware
app.use(cors());
app.use(express.json());

// mongodb driver code 
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@[link to mongodb]`;
console.log(uri);
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });

async function run() {
    try {
        await client.connect();
        const productCollection = client.db('emaJohn').collection('product');

        app.get('/product', async (req, res) => {
            const query = {};
            const cursor = productCollection.find(query);
            const products = await cursor.toArray();
            res.send(products);
        })
    }
    finally { }
}
run().catch(console.dir);


// setup root 
app.get('/', (req, res) => {
    res.send('Ema John Server is running...');
})

app.listen(port, () => {
    console.log('Listening to port ', port);
})

The program shows the following error, where I have used console.log() to display the contents of the URI for MongoDB.

mongodb+srv://undefined:undefined@[here goes my link to mongodb]
Listening to port  5000
MongoServerError: bad auth : Authentication failed.
    at Connection.onMessage (F:\Projects\ema-john-server\node_modules\mongodb\lib\cmap\connection.js:203:30)
    at MessageStream.<anonymous> (F:\Projects\ema-john-server\node_modules\mongodb\lib\cmap\connection.js:63:60)
    at MessageStream.emit (node:events:390:28)
    at processIncomingData (F:\Projects\ema-john-server\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
    at MessageStream._write (F:\Projects\ema-john-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) {
  ok: 0,
  code: 8000,
  codeName: 'AtlasError',
  [Symbol(errorLabels)]: Set(0) {}
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I mistakenly put ':' instead of '=' in the .env file. I have corrected it!

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda