I have done what I do in every project, I install dotenv with npm i dotenv
, I create my file .env
and call it in the file that I need it, first I require the module with require('dotenv').config
, and I initialize my variable const db = process.env.DB_CONNECTION
, however when I try to connect to the database I don't know I connected, I did a console.log(db)
and the log was undefined
. What is the error? I don't know why this happens. I have always worked with environment variables and this is the first time this has happened to me.
connection.js (connection file)
require('dotenv').config
const mongoose = require('mongoose')
const db = process.env.DB_CONNECTION
console.log(db) // devuelve undefined
const client = mongoose.connect(db,{ useNewUrlParser: true, useUnifiedTopology: true})
//no se conecta por que la variable no tiene un string como valor
.env file
DB_CONNECTION = miCadenaDeConexion
directory structure
proyecto
-db
-conexion.js
-index.js
-node_modules
-package.json
-.env
versions
node version = 14.1.0 dotenv
version = 8.2.0
.config
is a function so it must have parentheses()
.With this configuration it recognizes the file
.env
and the variables that are declared in it.I see an error where you require dotenv and call the config.
.config is a function so it must have parentheses.