0

This is my code, I had tried to set class value to db.db('mydb') to using in other function below

class Database {
    constructor() {
        this.db_url = "mongodb://127.0.0.1:27017/";
        let mongodb = require("mongodb").MongoClient;
        mongodb.connect(this.db_url, { useUnifiedTopology: true }, function(err, db) {
            if (err) throw err;
            this.dbo = db.db('mydb');
        })

    }
}

I tried to set dbo value of class = db.db('mydb') but I recieved this error

            this.dbo = db.db('mydb')
                     ^
TypeError: Cannot set property 'dbo' of undefined

but when i append console.log(db.db('mydb')) it still print out normally

jasonandmonte
  • 1,869
  • 2
  • 15
  • 24
bshanky
  • 1
  • 1

1 Answers1

1

As the error said: TypeError: Cannot set property 'dbo' of undefined, this is undefined in your callback function. What I understand is because the "context" is changed (you're in the callback function), this is no longer the same thing when you are in the constructor. You can refer to this popular answer for a formal explanation.

In your case, you can use a variable to hold the value of this

class Database {
    constructor() {
        this.db_url = "mongodb://127.0.0.1:27017/";
        var self = this; // add variable self which refer to the same object with this
        let mongodb = require("mongodb").MongoClient;
        mongodb.connect(this.db_url, { useUnifiedTopology: true }, function(err, db) {
            if (err) throw err;
            self.dbo = db.db('mydb'); // replace this by self
        })

    }
Đăng Khoa Đinh
  • 5,038
  • 3
  • 15
  • 33