skip to Main Content

i am trying to build a project but whenever i try to run my js code it shows me this 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. did not connect`

Here is my index.js-

import express from "express";
import bodyParser from "body-parser";
import mongoose from "mongoose";
import cors from "cors";
import dotenv from "dotenv";
import multer from "multer";
import helmet from "helmet";
import morgan from "morgan";
import path from "path";
import { fileURLToPath } from "url";

//configs(middleware)
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
dotenv.config();
const app = express();
app.use(express.json());
app.use(helmet());
app.use(helmet.crossOriginResourcePolicy({policy : "cross-origin"}));
app.use(morgan("common"));
app.use(bodyParser.json({limit : "30mb", extended : true}));
app.use(bodyParser.urlencoded({limit : "30mb" , extended : true}));
app.use(cors());
app.use("/assets", express.static(path.join(__dirname, 'public/assets'))); //set dir of where we keep assets(using it locally for now)

//file storage config
const storage = multer.diskStorage({
    destination : function(req,file,cb){
        cb(null,"public/assets");
    },
    filename : function(req,file,cb){
        cb(null,file.originalname);
    },

});
const upload = multer({storage});

//mongoose setup
const PORT = process.env.PORT || 6001;
mongoose.connect(process.env.MONGO_URL, {
    useNewUrlParser : true,
    useUnifiedTopology : true,
}).then(() => {
    app.listen(PORT, () => console.log(`Server Port : ${PORT}`));
})
.catch((error) => console.log(`${error} did not connect`));


and .env –

MONGO_URL='my url'
PORT=3001

I have been trying to fix this issue using forums/ chatgpt and bard but can’t seem to find a solution, pls help

2

Answers


  1. Your connection URL may be wrong, it should look like this:

    MONGO_URL = mongodb+srv://USER:[email protected]/DATABASENAME?retryWrites=true&w=majority
    
    Login or Signup to reply.
  2. .env file the variables should not be kept within string quote

    MONGO_URL=URL
    PORT=3001
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search