Home > database >  process.env.CONNECT_DATABASE is undefined while console.log
process.env.CONNECT_DATABASE is undefined while console.log

Time:12-21

const express = require("express");
const app = express();
const path = require("path");

require("dotenv").config({ path: path.resolve(__dirname, "./.env") });

const mongoose = require("mongoose");

console.log(process.env.DB_CONNECT);
// mongoose.connect(
//   process.env.DB_CONNECT,
//   { useNewUrlParse: true },

//   () => console.log("connected to db!")
// );

    const authRoute = require("./routes/auth");
    
    app.use("/api/user", authRoute);
    
    app.listen(3000, () => console.log("serve is up"));



const router = require("express").Router();

router.post("/register", (req, res) => {
  res.send("Register");
});

// router.post("/login");

module.exports = router;





DB_CONNECT="mongodb srv://<username>:<password>@fypdatabase.quhdl.mongodb.net/myFirstDatabase?retryWrites=true&w=majority"

I have installed mongoose, express, dotenv. I tried to connect user to the data base using dotenv, without dotenv it was working perfeclty fine:

moongoose.connect("url",{useNewUrlParser:true},console.log('connected');

But when I tried with dotenv and consolo logging the process.env.DB_CONNECT to see if there is value or not and it is showing undefined

CodePudding user response:

const dotenv = require('dotenv');
const mongoose = require('mongoose');

dotenv.config();

// console.log(process.env.MONGO_URL);

mongoose.connect(
  process.env.MONGO_URL,
  { useNewUrlParser: true, useUnifiedTopology: true },
  () => {
    console.log('database connected');
  }
);

CodePudding user response:

Maybe you specified wrong path to the .env file. Try to put .env file in the root of your application. Then just use config() without path option. .env package will by default check it for you in the root of the application.

require("dotenv").config();
  • Related