PHP User
PHP User

Reputation: 2422

NodeJS: inserting into MySQL error "Cannot read property 'query' of null"

I have simple 2 js files one is the entry point (main.js) and the other is the connection and methods. Here's the class

const mysql = require("mysql2/promise");

  class MySQLBackend {
    constructor() {
      this.connection = null;
    }

  async connect() {
    this.connection = await mysql.createConnection({
      host: "localhost",
      port: 3308,
      user: "root",
      password: "",
      database: "dbname",
    });
    return this.connection;
  }

  async disconnect() {
    this.connection.end();
  }

  async insert() {
    return this.connection.query(
      "insert into coins (value_date, coin_value) values ('2021-03-20 10:12:13', '4.25')"
    );
  }


  async test() {
    const connection = this.connect();
    if (connection) {
      console.log("connected!!"); //prints connected!!
      await this.insert();
    } else {
      throw new Error("Error connecting to mysql");
    }
  }
}

module.exports = MySQLBackend;

In main.js which is the entry point

const MySQLBackend = require("./services/backend/MySQLBackend");

async function runMySQL() {
  const mysqlBackend = new MySQLBackend();
  return mysqlBackend.test();
}

runMySQL()
  .then((result) => {
    console.log(result);
  })
  .catch((err) => console.error(err));

But I get

connected!!
TypeError: Cannot read property 'query' of null

I'm learning Node and don't know why I get this issue and how to solve it

Upvotes: 0

Views: 468

Answers (2)

PHP User
PHP User

Reputation: 2422

That's how I go t it to work

async insert() {
 return this.connection.query(
  "insert into table (field) values ('value')"
 );
}

async test() {
  *this.connection* = *await* this.connect();
  if (this.connection) {
    console.log("connected!!");
    await this.insert();
  } else {
  throw new Error("Error connecting to mysql");
  }
}

Upvotes: 1

fortunee
fortunee

Reputation: 4332

You need to bind the context of this for the test method within your MySQLBackend class constructor

So your constructor should look like this

constructor() {
   this.connection = null;
   this.test = this.test.bind(this)
}

Upvotes: 0

Related Questions