databasemongodbexpressmongoosebackend

Mongoose won't connect. - But no error in the console


I'm trying to connect my app.js to MongoDB. Worked the last time. This time, in this new project, it won't connect. And I don't get a console log. Neither get I an error-log. Is there something wrong in the code? or is ist a MongoDB problem. I tripple-checked the username and password.

.env-File:

PORT = 8080
MONGO_DB_CLIENT = "mongodb+srv://Admin:<mypassword>@g5-cluster0.vthttto.mongodb.net/?retryWrites=true&w=majority"

app.js

require('dotenv').config();
console.log(process.env.MONGO_DB_CLIENT);

const express = require('express');
const app = express();
const port = process.env.PORT;
const mongoose = require('mongoose');
const cors = require('cors');

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

const connectString = process.env.MONGO_DB_CLIENT;
app.use(async(req,res,next) => {
   try {
       await mongoose.connect(connectString,{
        useNewUrlParser: true,
        useUnifiedTopology: true,
    })
    console.log("Connected to MongoDB");
    next();

    } catch (error) {
        console.error(error);
    }
});

package.json dependencies

  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^16.3.1",
    "express": "^4.18.2",
    "mongoose": "^7.6.3"
  },
  • I tripple-checked the username and password.

  • Installed mongo db as well, didn't help. So i deleted it again. (i have mongoose)

  • i logged:

console.log(process.env.MONGO_DB_CLIENT);

...this works.

update - i tried:

async function connectToMongoDB() {
  try {
    console.log(process.env.MONGO_DB_CLIENT);
    await mongoose.connect(process.env.MONGO_DB_CLIENT, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    console.log('Connected to the DB ✅');
  } catch (error) {
    console.log(error);
  }
}

connectToMongoDB();

this is what the console said:

[1] MongoServerError: bad auth : authentication failed 
[1]     at MessageStream.<anonymous>
[1]   ok: 0,
[1]   code: 8000,
[1]   codeName: 'AtlasError',
[1]   connectionGeneration: 0,
[1]   [Symbol(errorLabels)]: Set(2) { 'HandshakeError', 'ResetPool' }

...so it must be a mongoDB authenication problem then i guess.. :/


Solution

  • try {
      console.log(process.env.MONGO_DB_CLIENT)
      await mongoose.connect(process.env.MONGO_DB_CLIENT);
      console.log( 'Connected to the DB ✅');
    } catch (error) {
      console.log(error);
    }
    

    Try this directly on the main file and check the console