Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

818
Visualizações
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 Respostas
Responde à pergunta

0

Here is how to use it as ES6 module

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

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda