node.jsmongodbmongoose

mongoose.connect(), URI parameter must be 'string', got 'undefined'. db.js and server.js issue


I am receiving this error message:

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.

This is my project structure

ROOT
|_ node_modules/
|_ package.json
|_ yarn.lock
|_ client/
|_ database/
|   |_ node_modules/
|   |_ db.js
|   |_ package.js
|   |_ .env
|   |_ yarn.lock
|_ server
    |_ controllers/
    |_ middleware/
    |_ routes/
    |_ server.js
    |_ package.json
    |_ yarn.lock 

I am able to connect to database if I call the database function inside db.js file like so:

require('dotenv').config()
const mongoose = require('mongoose')

// Database connection
const URI = process.env.ATLAS_URI
console.log(URI)

const mongoDB = async () => {
    try {
        // Passing additional connection parameters for connect()
        const connectionParams = {
            useNewUrlParser: true,
            useUnifiedTopology: true
        }
        
        // Connect to database
        await mongoose.connect(URI, connectionParams)

        // Log when connected to the database
        console.log('Connected to database ✅')

    } catch (error) {
        console.error('Error connecting to Database ❎\n', error)
    }
}

mongoDB()

However I use module.exports = mongoDB as a function to my server.js I encounter error. Here is the script for my server.js file

const express = require('express')
const mongoDB = require('../database/db')
const app = express()
const port = 1234

// Try to connect to the database
mongoDB()

// Start listening to the given port
app.listen(port, () => {
    console.log(`Server running on port ${port}`)
})

I have also checked my .env file and everything looks good also I have tested my connection string whether it is being read properly by logging the URI in the db.js file. I am able to see the connection string from the log. If anyone who has faced the similar issue. Please guide me through the process to fix this issue.


Solution

  • ok try give you dotenv package path option maybe it's fix your poblam

    require("dotenv").config({path:"your dotenv file path"})