I'm trying to insert User Matches in a table, but I don't want to repeat. Thus I'm running a COUNT query, but when I try to insert the new record I'm getting undefined so I can't insert the record.
I've read about using callbacks but being fairly new to NodeJS I'm currently struggling.
if(user_matches.length !== 0){
var connection = mysql.createConnection({
'host': 'localhost',
'user': 'root',
'password': '',
'database': 'test'
});
connection.connect();
//connection.query('TRUNCATE matches');
// I was originally truncating the table, but this just doesn't cut it
for (var x = 0; x < user_matches.length; x++){
var countQuery = connection.query('SELECT COUNT(*) as count FROM matches WHERE user_id_1 = ?', [ user_matches[x]['user_1']['id'] ]);
countQuery.on('result', function(){
// Here I get the UNDEFINED error, can't insert
connection.query('INSERT INTO matches SET ?', {
'user_id_1': user_matches[x]['user_1']['id'],
'user_id_2': user_matches[x]['user_2']['id']
});
});
}
connection.end();
}