节点JS mySQL三重查询和丢失信息

时间:2017-06-12 06:34:07

标签: mysql sql node.js database

在我的应用程序中,我有两个不同的表,它们通过第一个(一对多关系)的ID相互关联。它应首先以JSON格式从前端收集数据,如下所示:

cancellation = {
name: someting
id: someting
rule = 
[
 {someting}, {something}, {something}
] 
}

一张表用于取消,第二张用于规则。如果我想按此顺序放置这些信息,我需要先插入一条记录进行取消。然后进行查询以找出数据库中此记录的ID,然后使用此ID作为外键插入所有规则。但是,由于Node JS在获取有关记录程序星号ID的信息之前是异步的,因此执行其余代码并将此变量视为未定义。

app.post('/databaseSend/cancellation', function(req,res){
var cancellationReceived = req.body;
var cancellationID;
var rules = [];
var cancellation = [];
cancellation[0] = 
[
    cancellationReceived.name,
    cancellationReceived.id
]
// inserting data into cancellation table
connection.query("INSERT INTO cancellations (name, User_ID) VALUES ?", [cancellation],
    function(err,results){
        if(err){console.log(err)}

    }
)
//fetching ID of the current record
connection.query("SELECT id FROM cancellations WHERE User_ID = ? AND name = ?", [cancellationReceived.id, cancellationReceived.name],
    function(err, results){
        var cancellationID = results[0].id;
    });


//assigning ID to use it as a foreign key
for(var i = 0; i < cancellationReceived.rule.length; i++)
{
    rules[i] = 
    [
        cancellationReceived.rule[i].daysBefore,
        cancellationReceived.rule[i].fee,
        cancellationReceived.rule[i].type,
        cancellationID
    ]
}

for(var i = 0; i < rules.length; i++)
{
    console.log(rules[i]); // ID is undefined
}

});

我该如何解决这个问题?我试图使用setTimeout来暂停我的代码,但它没有改变任何东西。

我将此节点模块用于mysql - &gt; https://github.com/mysqljs/mysql

1 个答案:

答案 0 :(得分:1)

解决此问题的最佳方法是RTFM。

connection.query('INSERT INTO cancellations (name, user_id) values ?', [cancellation], function(err, results) {
    if (err)
       return console.error(err);

    // See https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row
    var cancellation_id = results.insertId;

    // Generate sql for rules, join them by ; and execute as one query
    // See https://github.com/mysqljs/mysql#multiple-statement-queries 
    connection.query(sqls, function(err) {
        if (err)
             return console.error(err);

        // Send response here
    });
})