Home > Back-end >  I'm trying to initialize a database connection but I get a The `uri` parameter to `openUri()` m
I'm trying to initialize a database connection but I get a The `uri` parameter to `openUri()` m

Time:08-19

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?

CodePudding user response:

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.

  • Related