I cannot access SQL query property on Node.js

Asked

Viewed 134 times

0

I’m trying to create a code that logs into a website, but when it takes the data from the database to do a check, I get an error.

My current code:

router.post('/loginClin', function(req, res, next) {
  var query = "SELECT * FROM bdlabella.tbclientes WHERE email_cli = ?",
    /// ;            será preenchido pelo mysql com o valor informado ^ 
        where = [ req.body.email_login ];
    /// ;                  ^ valor informado

    conn.query( query, where, (err, results) => {


    console.log('bd: '+results.email_cli); // nesse memento no cmd aparece bd: undefined
        if(err){
            console.log(err);
        }
        if( results && results.length > 0 ){  
            if(results.email_cli == req.body.email_login && results.senha_cli == req.body.senha_login){
              loginClin.render(1 ,req, res, null, null);
              console.log("entrou");
            } else{
            loginClin.render(2, req, res, 'Email ou senha Incorretos1', null, results);
            console.log("Email ou senha Incorretos1");
          }
        }
        else{
          loginClin.render(2, req, res, 'Email ou senha Incorretos2', null);
          console.log("Email ou senha Incorretos2");
        }
    });
});

The following line:

console.log('bd: ' + results.email_cli)

Produces the output:

bd: undefined
  • What is the result of console.log(results) on the console?

  • console.log('bd: '+Results.email_cli); // in this memory cmd appears bd: Undefined

  • console.log('bd: '+Results); // in that memento cmd appears bd: [Objets Objets ] something like this

  • Do not use console.log('bd: '+results). Use only console.log(results) and edit your answer by adding the returned value. If you try to concatenate into a string, will not be able to prove right.

  • [ Textrow { cod_cli: 2, cli_name: 'Samuel Melo da', sob_cli: 'Silva', phone_cli: '997356115', email_cli: '[email protected]', cli: '123', active: 1 } ]

1 answer

0


The problem is that your query is not returning a single object, but rather a list of objects. In your case, the return is exactly this:

[
  TextRow {
    cod_cli: 2,
    email_cli: 'Algum Valor',

    // Demais propriedades...
  }
]

Thus, to access first returned object, you must do:

results[0].email_cli

If you want, however, to scroll over each returned property, you must use a loop for. Something like:

for (const row of result) {
    console.log(row.email_cli)
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.