1

i have a database.js file. in this file i have 3 functions named connect, getDb and disconnect. when i use exports (the below code) , the require function loads nothing! and when i use module.exports, every thing goes in the right way! whats wrong with exports here?

// my database.js file

const MongoClient = require('mongodb').MongoClient;

const database_name = 'car-repair';
const uri = `mongodb://localhost:27017/${database_name}`;

let database;

const connect = () => {
  let options = {
    useNewUrlParser: true,
    useUnifiedTopology: true
  };

  try {
      MongoClient.connect(uri, options, (err, db) => {
          database = db;
          console.log('connected to database.');
      });
  } catch (e) {
      console.log(e);
  }
};

const getDB = () => database;

const disconnect = () => database.close();

exports = {
    connect, getDB, disconnect
};

if i use the code like the below, it returns undefined

// my app.js file
const database = require('./database');

console.log(database.connect); // undefined!

when i change the exports to module.exports everything works properly.

module.exports = {
    connect, getDB, disconnect
};

whats wrong with exports?

Mahdi
  • 187
  • 2
  • 14
  • By itself, `exports` would be a variable. Maybe you are mistaking it as the ES6 syntax with `export` or `export default` ? – Seblor Dec 15 '19 at 20:05
  • @seblor have you seen the code? i have not used es6 `default`. review the code i have written at the top. (database.js) – Mahdi Dec 15 '19 at 20:08
  • 2
    There is a lot of good info here: https://stackoverflow.com/questions/16383795/difference-between-module-exports-and-exports-in-the-commonjs-module-system – Michael Rodriguez Dec 15 '19 at 20:11
  • @Mahdi yes I have read your code. And my comment was asking if maybe you were mixing the 2 syntaxes... – Seblor Dec 15 '19 at 20:12
  • @MichaelRodriguez thanks. this is the right answer :) – Mahdi Dec 15 '19 at 20:15
  • @Seblor the `exports` is a variable that references to `module.exports`. if we change it completely, the reference will be changed and it will not set values to `module.exports` any more. – Mahdi Dec 15 '19 at 20:19
  • What do you mean "exports is a variable that references to module.exports" ? I don't see any `const exports = module.exports` anywhere in your code. Again, by itself, `exports` would be a variable. `exports` is not a keyword. – Seblor Dec 15 '19 at 20:21

0 Answers0