Reputation: 591
My code:
require('dotenv').config();
var mongoose = require('mongoose');
var gracefulShutdown;
var dbURI = 'mongodb://localhost/Loc8r';
if (process.env.NODE_ENV === 'production') {
dbURI = process.env.MONGOLAB_URI;
}
mongoose.connect(dbURI);
and after running NODE_ENV=production nodemon i got this error
(node:10624) UnhandledPromiseRejectionWarning: Error: URL malformed, cannot be parsed
if i manually set dbURI, it works perfectly fine
dbURI = 'mongodb://<dbuser>:<dbpassword>@ds****.mlab.com:****/database'
Upvotes: 1
Views: 1802
Reputation: 180
I'm having the same problem, don't know if the scenario is the same as yours but basically I have this node script which connects to MongoDB via the NodeJS Driver (no Mongoose) and I run this script via a *NIX cron job.
Anyways, reading the dotenv docs I found out that you can actually parse the config results doing something like this:
const dotenv = require('dotenv')
const result = dotenv.config()
if (result.error) { throw result.error }
console.log(result.parsed)
I did and turns out my script is assuming my .env file is on user's home, not project root (yes, I'm running this on an AWS EC2). The error is pretty clear:
Error: ENOENT: no such file or directory, open '/home/ec2-user/.env'
So yeah, make sure your .env file is accessible from within the script execution directory (in my case I'm executing the script from /home/ec2-user and my project root dir is /home/ec2-user/project).
TL;DR: specify .env location via absolute path, like this
require('dotenv').config({path: '/full/custom/path/to/your/.env'})
Upvotes: 3