如果ID未find,如何插入行?

我试图在表中插入用户匹配,但我不想重复。 因此,我正在运行COUNT查询,但是当我尝试插入新logging时,我得到了未定义的信息,因此无法插入logging。

我已经阅读了有关使用callback,但对NodeJS是相当新的,我目前正在挣扎。

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(); } 

安装async

npm install async --save

然后试试这个:

 if(user_matches.length !== 0){ var connection = mysql.createConnection({ 'host': 'localhost', 'user': 'root', 'password': '', 'database': 'test' }); connection.connect(); async.each(user_matches, function(x, callback){ var countQuery = connection.query('SELECT COUNT(*) as count FROM matches WHERE user_id_1 = ?', [ x['user_1']['id'] ]); countQuery.on('result', function(){ var insertQuery = connection.query('INSERT INTO matches SET ?', { 'user_id_1': x['user_1']['id'], 'user_id_2': x['user_2']['id'] }); insertQuery.on('result', callback); }); }, function(err){ console.log('done'); }); }