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}`)
There are several methods to import dotenv configs, 2u4u has been answered one of the way to import dotenv, and you can try this one below too for your future reference.
import { configDotenv } from "dotenv";
import express from "express";
const app = express();
configDotenv();
app.get("/" , (req, res) => {
return res.json("HELLO WORLD")
});
app.listen(process.env.PORT, () => {
console.log(`This app listens to http://localhost:${process.env.PORT}`)
});
Since the configDotenv
is a function, and I checked with console.log
for a better clarification though, then you need to call below. That's it and worked for me too.