Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rethrow non-MySQL errors Node.js

Tags:

node.js

npm

mysql

Hi the code below loads a single field from a mysql database, but when it gets to the point result[0].IdUtente the error below is generated. How do I solve it?

ERROR:

 throw err; // Rethrow non-MySQL errors
        ^

TypeError: Cannot read property 'IdUtente' of undefined

CODE:

var query = "SELECT IdUtente FROM Utente WHERE Username = " + sql.escape(Username) + " and Password=MD5(" + sql.escape(Password) + ") and Tipo!='Risorsa' ";
var ret=DbConfig.query(query, function (err, result) {
    if (err) {
        console.log("Errore login: " + err);
    }
    else {
        console.log(result[0].IdUtente);
        IdUtente = result[0].IdUtente;

    }

});
like image 543
riki Avatar asked May 29 '26 19:05

riki


1 Answers

This error occur when the query pulls an empty result. You must first check the length of result with result.length property, only if the result is greater than 0 you must use index the result. Please check the code below.

var query = "SELECT IdUtente FROM Utente WHERE Username = " + sql.escape(Username) + " and Password=MD5(" + sql.escape(Password) + ") and Tipo!='Risorsa' ";
var ret=DbConfig.query(query, function (err, result) {
    if (err) {
        console.log("Errore login: " + err);
    }
    else {
        //check to see if the result is empty
        if(result.length > 0){
            console.log(result[0].IdUtente);
            IdUtente = result[0].IdUtente;
       }
    }
});
like image 172
Aslam Avatar answered May 31 '26 08:05

Aslam