Hopp2
Hopp2

Reputation: 15

I'm trying to initialize a database connection but I get a The `uri` parameter to `openUri()` must be a string error

The error on terminal

:\Users\HOPE\Tutorial_API\node_modules\mongoose\lib\connection.js:694 throw new MongooseError('The uri parameter to openUri() must be a ' + ^

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. at NativeConnection.Connection.openUri (C:\Users\HOPE\Tutorial_API\node_modules\mongoose\lib\connection.js:694:11) at C:\Users\HOPE\Tutorial_API\node_modules\mongoose\lib\index.js:380:10 at C:\Users\HOPE\Tutorial_API\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5 at new Promise () at promiseOrCallback (C:\Users\HOPE\Tutorial_API\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10) at Mongoose._promiseOrCallback (C:\Users\HOPE\Tutorial_API\node_modules\mongoose\lib\index.js:1225:10) at Mongoose.connect (C:\Users\HOPE\Tutorial_API\node_modules\mongoose\lib\index.js:379:20) at connectDatabase (C:\Users\HOPE\Tutorial_API\config\db.js:5:14) at Object. (C:\Users\HOPE\Tutorial_API\server.js:7:23) at Module._compile (node:internal/modules/cjs/loader:1105:14)

my server.js file

const express = require('express');
const health = require('./routes/healthChecker.routes');
const app = express();

require('./config/db')();

app.use(express.json());

app.use('/health', health)


const port = process.env.PORT || 3000
app.listen(port, () => {
    console.log(`Listening on port ${port}`)
});

my database file

const mongoose = require('mongoose');

const connectDatabase = () => {
    mongoose.connect(process.env.DB_LOCAL_URI, {
            useUnifiedTopology: true
        })
        .then((con) => {
            console.log(`MongoDB Database connected to host ${con.connection.host}`);
        });
}

module.exports = connectDatabase;

my default.json file

{
    "values": {
        "url": "http://localhost:3000/",
        "DB_LOCAL_URI": "mongodb://localhost:27017/"
    }
}

what might be the issue?

Upvotes: 1

Views: 391

Answers (3)

Naomi Rono
Naomi Rono

Reputation: 21

Connection error: MongoParseError: Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"

Someone might also encounter the issue above and I've found a solution that might help you resolve this issue. It's related to the format of the MONGODB_URI in your .env file. Here's what you can do:

Step 1: Review Your .env File

Check your .env file where you store your MongoDB connection string. Make sure the format starts with either "mongodb://" or "mongodb+srv://". You might be encountering this error if the scheme is incorrect.

Step 2: Remove Semicolon from MONGODB_URI

It appears that a common issue causing this error is having a semicolon (;) at the end of the MONGODB_URI in the .env file. Make sure your MONGODB_URI does not end with a semicolon.

For example, ensure your .env file looks like this (without the semicolon at the end):

MONGODB_URI="mongodb+srv://username:[email protected]/?retryWrites=true&w=majority"

Step 3: Restart Your Application

After making the changes in your .env file, save the file and restart your Node.js application to ensure the updated configuration is loaded.

Upvotes: 1

Naomi Rono
Naomi Rono

Reputation: 21

Connection 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.

The issue can be resolved by utilizing the dotenv package to manage environment variables in your project. Here's how I managed to fix the error:

Step 1: Install dotenv

First, install the dotenv package by running the following command in your project directory:

npm install dotenv

Step 2: Configure Your .env File

Create a .env file in the root directory of your project and add your MongoDB connection string as an environment variable:

MONGODB_URI="mongodb+srv://username:[email protected]/?retryWrites=true&w=majority"

Step 3: Modify db.js/server.js

In your db.js file, require and configure dotenv at the beginning of the file:

require('dotenv').config(); // Load environment variables from .env file

const mongoose = require('mongoose');

mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
        console.log('Connected to the database');
    })
    .catch(err => {
        console.error('Connection error:', err.message);
    });

By requiring and configuring dotenv in your db.js/server file, the environment variables from your .env file will be available, including the MONGODB_URI value.

Upvotes: 1

Stephen Taylor
Stephen Taylor

Reputation: 868

I think you're mixing up two ways to include environment variables.

The first way is the one you've chosen: to use a default.json file which uses the config npm package

npm i config

const config = require('config');

you can then use parameters from your default.json file this way:

config.get('values.DB_LOCAL_URI');

ie.

const mongoose = require('mongoose');

const connectDatabase = () => {
    mongoose.connect(config.get('values.DB_LOCAL_URI'), {
            useUnifiedTopology: true
        })
        .then((con) => {
            console.log(`MongoDB Database connected to host ${con.connection.host}`);
        });
}

module.exports = connectDatabase;

The second way is to use a .env file which lives in your node file's directory as looks like this:

URL = "http://localhost:3000/"
DB_LOCAL_URI = "mongodb://localhost:27017/"

Install dotenv package:

npm i dotenv

You access your .env file with a require statement in your server.js file (which references your database file):

server.js

require('dotenv').config();

and then by using this pattern:

process.env.DB_LOCAL_URI

like this:

const mongoose = require('mongoose');

const connectDatabase = () => {
    mongoose.connect(process.env.DB_LOCAL_URI), {
            useUnifiedTopology: true
        })
        .then((con) => {
            console.log(`MongoDB Database connected to host ${con.connection.host}`);
        });
}

module.exports = connectDatabase;

In summary, you've used the pattern (process.env.MYVARIABLE) of the second method, whereas you're trying to access the environmental/settings file (default.json) using the first method.

Upvotes: 0

Related Questions