Node mysql TypeError: conn.beginTransaction is not a function

I have a mysql query I am trying to perform with node-mysql that uses a transaction. It should be on the connection object, but the error I am getting says that it doesn’t have a begin transaction method.

TypeError: conn.beginTransaction is not a function

Here’s the transaction code:

dbutil.transaction(req.db, 

    function(done){

        req.db.query('INSERT INTO answers (question, user, background, importance, comment) values (?, ?, ?, ?, ?)',
            [question, user, background, concurrence, importance, comment],  function (err, result){
                console.log('result from insert query: ', result);
                console.error('error: ', err);
                done();
            // req.db.query('INSERT INTO concurrenceAnswers (concurrence) values (?)',
            //     [concurrence], function (err, result){
            //         console.log('result form insert query: ', result);
            //         console.error('error: ', err);

            // })

        });


    }, function(){}

    );

And the transaction method:

exports.transaction = function(conn, body, done) {
    conn.beginTransaction(function(err) {
        if (err) return done(err);

    body(function(err) {
        if (err) return conn.rollback(function() {
            done(err);
        });

        conn.commit(function(err) {
            if (err) return conn.rollback(function() {
                done(err);
            });

            done();
        });
    });
});
};

Req.db.query is:

var db = mysql.createPool({
connectionLimit: config.db.connectionLimit,
host:            config.db.host,
user:            config.db.user,
password:        config.db.password,
database:        config.db.database,
port:            config.db.port

});

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

As you are using a pool you need first to get the connection from the pool (You cannot use the pool directly to begin a transaction like you can be for a query):

exports.transaction = function(connection, body, done) {

  connection.getConnection(function(err, conn) {

    conn.beginTransaction(function(err) {
      if (err) return done(err);

      body(function(err) {
        if (err) return conn.rollback(function() {
          done(err);
        });

        conn.commit(function(err) {
          if (err) return conn.rollback(function() {
            done(err);
          });

          done();
        });
      });
    });
  });
};

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply