1

I have a Database object (database.js) that looks like this:

//create the database 
function Database(host, dbuser, dbpassword){
    this.host = host;
    this.dbuser = dbuser;
    this.dbpassword = dbpassword;
    this.connection = null;
}

Database.prototype = {
    connection: function(){
        this.connection = mysql.createConnection({
            host: host,
            user: dbuser
        });
    },
    createDatabase: function(){...};

I'm then importing this object into my main app.js using a require statement

var db = require('./database.js');

However, when I try to construct my database object, I get a TypeError Database is not a constructor

var connection = new db('localhost','root');
connection.connection();

What am I doing wrong here? I read up on prototypes and it seems that I'm not lacking anything in that department so it seems that it has something to do with my require statement?

6
  • Because node.js support ES6 by default now, use class. It will makes your code easier and you gonna avoid errors like this. Commented Sep 25, 2017 at 15:43
  • But is there any reason this prototype wont work? I'd have to read up on classes but I thought prototypes were still supported... Commented Sep 25, 2017 at 15:45
  • How did you exported Database in your file database.js? Commented Sep 25, 2017 at 15:48
  • I did exports.Database = Database; Commented Sep 25, 2017 at 15:49
  • {host: host, user: dbuser}{host: this.host, user: this.dbuser} Commented Sep 25, 2017 at 15:52

1 Answer 1

2

To export your Database "class" use

module.exports = Database;

And to use

var Database = require('./database.js');

new Database(...);

Here you have a good tutorial about how to use export/require


Is still strongly recommend to upgrade to ES6.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahh thank you so much! Worked perfectly! Still iffy on the workings on Node but this seemed to fix my problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.