-3

If I do the following:

// at the end of database.js
module.exports = mongoConnect;
module.exports = getDb;

// app.js
const mongoConnect = require('./util/database').mongoConnect;
mongoConnect();

I get the error: ERROR: mongoConnect is not a function.

But if I instead export them like this:

// at the end of database.js
module.exports = {
    mongoConnect,
    getDb,
};

Then running console.log(mongoConnect) in app.js gives the following:

{
    mongoConnect: [Function: mongoConnect],
    getDb: [Function: getDb],
}

and app.js can use mongoConnect just fine.

Why can't I use the first format?

Kelvin Schoofs
  • 8,323
  • 1
  • 12
  • 31
feedback
  • 3
  • 1
  • 3
  • The second line is overwriting the ``exports`` containing ``mongoConnect`` – Majed Badawi Jul 21 '21 at 17:28
  • 1
    For the same reason why `x` cannot be both `1` and `2` when you do `var x; x = 1; x = 2;`. – Sebastian Simon Jul 21 '21 at 17:29
  • Even though this question shows some lack of basic JS knowledge, I'm not sure it's a reason to downvote it. Seems like a genuine question to me, worth answering. – Kelvin Schoofs Jul 21 '21 at 17:31
  • @KelvinSchoofs See [How much research effort is expected of Stack Overflow users?](//meta.stackoverflow.com/q/261592/4642212). The tooltip on the downvote arrow says _“This question does not show any research effort; it is unclear or not useful”_. I can’t spot any research by the OP. – Sebastian Simon Jul 21 '21 at 17:37
  • fair enough @SebastianSimon, but i did some research. i had this problem because in a tutorial it worked for him doing 2 times module.exports and not for me, that's why i tilted. but i think under the hood he change it – feedback Jul 21 '21 at 17:44
  • @feedback Which tutorial? – Sebastian Simon Jul 21 '21 at 18:40
  • @SebastianSimon is in udemy, but after watching the video from the beginning he changed it. i was just tired ahahah sorry to bother you, and others, i really appreciate this fast-help. love this comunity. – feedback Jul 21 '21 at 20:07

1 Answers1

2

You are overwriting the exports, thus only the last value is saved. Besides, when directly assigning exports, then require('...') will be that exact exports.

Your second example is how you're meant to export multiple values:

// module
module.exports = {
    mongoConnect,
    getDb,
};

// other module
const module = require('./module');
module.getDb(...);

// or alternatively
const { getDb } = require('./module');
getDb(...);
Kelvin Schoofs
  • 8,323
  • 1
  • 12
  • 31
  • ok thanks sir, im new in nodejs. this helped me alot to understand what is happening :https://stackoverflow.com/questions/7137397/module-exports-vs-exports-in-node-js/26451885#26451885 – feedback Jul 21 '21 at 17:35
  • Don't forget to mark the correct answer as the solution to your question. – Kelvin Schoofs Jul 21 '21 at 17:39