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

820
Vistas
How to use .env with ES6 module with node js and express application?

I need your help on how I can use .env file on this application. here is my problem: I am building an app using ES6 module in my node express app. I am facing a problem while storing my variable in .env file, both these two ways below are giving 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. But when I only use the plain string connect is working, that means that I am not using the dotenv file correctly:

1-

import {} from "dotenv/config.js";
import express from "express";
import mongoose from "mongoose";
import cors from "cors";

const app=express()
...
//DB config
mongoose.connect(process.env.CONNECTION_URL,
    {
      useCreateIndex: true,
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })

app.listen(port,()=>console.log(`server on ${port}`) 

2-

import dotenv from "dotenv";
import express from "express";
import mongoose from "mongoose";
import cors from "cors";

dotenv.config();

const app=express()
...
//DB config
mongoose.connect(process.env.CONNECTION_URL,
    {
      useCreateIndex: true,
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })

app.listen(port,()=>console.log(`server on ${port}`)
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Here is how to use it as ES6 module

import * as dotenv from 'dotenv';
dotenv.config();
over 4 years ago · Santiago Trujillo Denunciar

0

You are right, you are not fetching the env variables.

I'll tell you how I do it. Just create a .env file with your variables.

Then in your app.js:

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

And to use the variable uri you have in the .env

const foo = process.env.uri
over 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