Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

236
Vistas
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?

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda