Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Error when trying to connect to Mongo DB

so my problem is I'm trying to connect my application to a Mongo DB collection/ database and it won't connect. I have my connection string and port number in a .env file and then I import it into my app.js file, where I try to make a connection.

Error in the console log :

throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
^
Error [MongooseError]: The `uri` parameter to `openUri()` must be a string, got "undefined". Make 
sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.

.env file :

MONGO_URI=mongodb+srv://Admin:<Password>@cluster0-3t4ed.mongodb.net/test?retryWrites=true&w=majority
PORT=3000

app.js file :

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const morgan = require("morgan");
const dotenv = require("dotenv");
dotenv.config();

Database :

mongoose.connect(process.env.MONGO_URI).then(() => {
  console.log("DB Connected");
});

mongoose.connection.on("error", err => {
 console.log(`DB Connection Error: ${err.message}`);
});

I've already put the connection string in quotes and all, it still didn't work.

I've talked to the MongoDB support and they couldn't help me.

Any suggestions would be very helpful.

like image 876
ddd Avatar asked Dec 01 '25 03:12

ddd


1 Answers

You are receiving this message because MONGO_URI is undefined when mongoose.connect(process.env.MONGO_URI) is called.

The solution is to call dotenv.config() as early as possible in your application (see dotenv documentation).

// app.js
require("dotenv").config();
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const morgan = require("morgan");
like image 133
Fcmam5 Avatar answered Dec 02 '25 19:12

Fcmam5