2

Here is my index.js:

import dotenv from 'dotenv'
dotenv.config();
import "./WebScrapingProject/DBConnect";

If I ran the code above I get this error:

The `uri` parameter to `openUri()` must be a string, got "undefined".

But if I changed imports to ES5:

import dotenv from 'dotenv'
dotenv.config();
require("./WebScrapingProject/DBConnect");

it works but why? and how can I use ES6 imports in this case?

Here is the DBConnect file:

import {default as mongo} from "mongoose";

mongo.connect(process.env.DB_HOST, {useNewUrlParser: true}).then(() => {console.log('DB connected!')});
mongo.set('useFindAndModify', false);
2
  • what was an error ? please elaborate it more still confused about the way you are doing you want to use import for importing all packages ? Commented Aug 4, 2019 at 11:27
  • the error is in the post Commented Aug 4, 2019 at 12:09

2 Answers 2

5

There are two different choices on which module system we can be use:

Importing modules using require also CommonJS Importing modules using ES6 import.

The behaviour of both modules system are different when you do require Loading is synchronous. That means if you have multiple requires, they are loaded and processed one by one.

and when import can be asynchronous (and in current ES6 Module Loader, it in fact is) and can perform a little better.

In your case mongoose did not get configuraiton settings thats why it throws error, due to which config file was not loaded yet

The problem is the import happens before dotenv has loaded your env config file.

solution is to put the env config in a separate file and import it first or change the order

// index.js
import './loadEnv';
import './WebScrapingProject/DBConnect';

// loadEnv.js
import dotenv from 'dotenv';
dotenv.config()
Sign up to request clarification or add additional context in comments.

1 Comment

If I needed to do this on every time then ES6 is pretty much pointless..., I will go back to ES5 it's better, anyway thanks for the explanation
4

The problem is the import happens before dotenv has loaded your env config file. This is because all the imports are loaded before the other code in the file is run.

One way of fixing it is to put the env config in a separate file and import it first.

e.g.

// index.js
import './loadEnv';
import './WebScrapingProject/DBConnect';
// loadEnv.js
import dotenv from 'dotenv';
dotenv.config()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.