dankqheed
dankqheed

Reputation: 13

TypeError: Database is not a constructor when initializing constructor

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?

Upvotes: 1

Views: 6814

Answers (1)

Orelsanpls
Orelsanpls

Reputation: 23515

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.

Upvotes: 2

Related Questions