Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

});

like image 862
realisation Avatar asked Jan 08 '23 13:01

realisation


1 Answers

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();
        });
      });
    });
  });
};
like image 137
Thibault Clement Avatar answered Mar 15 '23 16:03

Thibault Clement