Home > Software engineering >  MongoDB authentication not working due to dotenv
MongoDB authentication not working due to dotenv

Time:05-02

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) {}
}

CodePudding user response:

if you are using mongoDB Atlas

you can try this


    const mongoose = require('mongoose');
    mongoose.connect("mongodb srv://"   DB_USER   ":"   DB_PASS   "@<your url>.mongodb.net/<yourCollection>");

and to start the server you can use this code


    let port = process.env.PORT;
    if(port == null || port == ""){
        port = 3000;
    }
    app.listen(port, () => {
        console.log("server started at "   port);
    });

CodePudding user response:

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

  • Related