I have got a configuration file called dev.js
which contains an object that has a key called dbURL
which holds database url for MongoDB. It looks like this exactly.
export const config = {
dbURL: 'mongodb srv://...'
}
And I have got another file called db.js
where I import the above dev.js
file and use the dbURL
key in order to connect to the database.
import { connect as _connect } from 'mongoose';
import {config} from '../config/dev';
const connect = (url = config.dbURL, opts = {}) => {
return _connect(
url,
{}, err => {
if (err) throw err;
console.log('Connected to MongoDB!')
}
)
}
export default connect;
The problem is if I tried to change the dbURL
's value in the dev.js
file to be process.env.DEV_DB
for example.
export const config = {
dbURL: process.env.DEV_DB
}
The .env
file looks like this
DEV_DB = "mongodb srv://...."
It actually returns undefined
, although I tried to console.log(process.env.DEV_DB)
in the db.js
file and it printed the database url normally.
import { connect as _connect } from 'mongoose';
import {config} from '../config/dev';
const connect = (url = config.dbURL, opts = {}) => {
console.log(config) //logs {dbURL: undefined}
console.log(process.env.DEV_DB) //logs the database url normally
return _connect(
url,
{}, err => {
if (err) throw err;
console.log('Connected to MongoDB!')
}
)
}
export default connect;
When I tried to log the process.env.DEV_DB
in the dev.js
file, it logged undefined
as well.
Note: The dotenv
is imported at the top of the application, and the .env
is in the root file.
CodePudding user response:
Have you imported dotenv at the top of your dev.js file as well? That solved it for me when I tried it locally.