Search code examples
javascriptmysqlnode.jsnode-mysql

node-mysql: error when using object.query


I'm learning nodejs and using 'mysql' module. With this function I want to verify if a name already exists in the database.

I have the current error

TypeError: Object #<Handshake> has no method 'query'

I think it is related to "this.query" but can't find a way to fix it.

Code

var mysql = require('mysql');
var conexao_bd = mysql.createConnection({
    host: 'localhost',
    user: 'user',
    password: 'password',
    database: 'db_name'
});

function verifica_nome(n){
    var bool = false;
    conexao_bd.connect(function(err){
        if(err){
            return console.log("Aconteceu um erro quando se tentava ligar à base de dados. Erro: "+err);
        }
        else{
            this.query("SELECT name FROM Users WHERE name=?", [n], function(err,rows){
                if(err != null){ this.end("Erro na query: "+err); }
                else{
                    if(rows[0]!=n){ bool=true; this.end(function(err){ return bool;})}
                    else{ this.end(function(err){ return bool;})}
                }
            });
        }
    });
}

Solution

  • You should use conexao_bd, which is the connection object, and not this:

    conexao_bd.query(...);
    conexao_bd.end();