Sunday 11 June 2017

Node JS mySQL tripple query and lost of information

In my application I have a two different tables related to each other by ID of the first one (one to many relation). It should first collect the data from the frontend-side by in JSON format which looks like this:

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

One table would be for cancellation and the second one for the rules. If I want to put those information in this order I need first insert one record for cancellation. Then make a query to find out what is an ID of this record in the database and after that insert all rules using this ID as a foreign key. But since Node JS is asynchronous before I fetch the information about the ID of the record program stars to execute rest of the code and consider this variable as undefined.

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
}

});

How can I solve this problem? I tried to use setTimeout for pausing my code but it did not change anything.

And I use this node module for mysql - > https://github.com/mysqljs/mysql



via andrzej541

No comments:

Post a Comment