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
});
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();
});
});
});
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With