1

I am trying to connect to my MongoDB database using a env variable that is in my config.env file so that I don't leave my connection string visible for everyone, but I keep getting the error that my DB_URL is not defined, why? How should I do it? I installed env2, then I created my confing.env which looks like this:

export DB_URL='mongodb://admin:username@password/heroku_url';

and then I required it in my server js which looks like this:

// Requiring the dependencies
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const PORT = process.env.PORT || 3001;
const itemRoutes = express.Router();
let Comment = require('./comment.model');
require('env2')('../config.env')

app.use(cors());
app.use(bodyParser.json());


mongoose.connect(DB_URL, { useNewUrlParser: true } )

const connection = mongoose.connection;

connection.once('open', function() {
  console.log('Connection to MongoDB established succesfully!');
});

// Serve static assets
if(process.env.NODE_ENV === 'production') {
  app.use(express.static('build'));
}

itemRoutes.route('/').get( async (req, res) => {
  let collection = connection.collection("posts");
  let response = await collection.find({})
  .toArray();
  res.send(response);
});

itemRoutes.route('/comments').get( async (req, res) => {
  let collection = connection.collection("comments");
  let response = await collection.find({})
  .toArray();
  res.send(response);
});

itemRoutes.route('/userComments')
.post((req, res) => {
   res.setHeader('Content-Type', 'application/json');
   let comment = new Comment(req.body);
   comment.save()
   .then(comment => {
     res.status(200).json({comment})
   })
   .catch(err => {
     res.status(400).send('failed')
   })
});


app.use('/', itemRoutes);
app.use('/userComments', itemRoutes);


app.listen(PORT, function() {
  console.log('Server is running on' + ' ' + PORT);
})

1 Answer 1

1

Instead of using DB_URL, you should use process.env.DB_URL

Like this: mongoose.connect(process.env.DB_URL, { useNewUrlParser: true } )

Check out the docs: https://www.npmjs.com/package/env2#use-in-your-code

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.