Haus
Haus

Reputation: 1492

NodeJS/ES6: Cannot set property of undefined

Using NodeJS/ES6 I have created a MongoDB connector class.

class DBClient {

    constructor(host, port) {
        this.host = host;
        this.port = port
        this.dbConnection = null;
    }

    buildConnectionString() {
        return 'mongodb://' + this.host + ':' + this.port;
    }

    connect() {
        var connectionString = this.buildConnectionString();
        console.log('[MongoDB] - Connecting to instance @ ' + connectionString);
        var DBConnection = MongoClient.connect(connectionString, function(error, db) {
            if (error) {
                console.log('[MongoDB] - Error connecting to instance');
                console.log(error);
            }
            else {
                console.log('[MongoDB] - Connection Successful');
                this.dbConnection = db;
            }
        });
    }
}

Which is then being created in a different file like so

var client = new DBClient('127.0.0.1', '1337');
client.connect();

When the database is connected to, NodeJS crashes when it reaches this.dbConnection = db;, stating TypeError: Cannot set property 'dbConnection' of undefined.

I'm pretty sure it has something to do with being used in a callback, which is screwing up the scope. How can I get around this though? Wouldn't any operation from the callback scope be isolated and unable to reference this?

Also, as a side question, is this a bad code practice to initialize a null property like I'm doing in the constructor? If so, what would be a more proper way of doing it?

Upvotes: 0

Views: 879

Answers (1)

andrea06590
andrea06590

Reputation: 1299

Indeed if you want to keep your scope use lambda instead like :

var DBConnection = MongoClient.connect(connectionString, (error, db) => 
      {
        ...
      });

if you have to keep your function because of your transpilation settings or the lib does not support lambda, save your scope in a variable like :

var self = this;
var DBConnection = MongoClient.connect(connectionString, function(error, db)  
      {
        ... self.dbConnection = db;
      });

Upvotes: 1

Related Questions