Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
Unable to get mysql count in node.js route

I am new to node.js, and currently working on demo project so my requirement is to get count of userId which I am calling by function and this function is declared outside of route, but I am getting undefined but in same function getting count values but when I returned count still getting undefined in route.

Code:

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {      
    const usersQuery = "SELECT * FROM users";
    dbConn.query(usersQuery,function(err,rows)     {
        if(err) {
            console.log('this error',res);
        } else {
            let total=getCount();   // calling function placed outside
            console.log(total);
            }
        
        });
    });

Function declared outside to return count:

function getCount(){
    const usersQuery = "SELECT count(id) as cnt FROM users";
    dbConn.query(usersQuery,function(err,rows)     {
        if(err) {
            console.log('failed  to get count');
        } else {
            return rows; // retun count 
          
            }
    })
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You need to return the result of the query

function getCount(){
    const usersQuery = "SELECT count(id) as cnt FROM users";
    return dbConn.query(usersQuery,function(err,rows)     {
        if(err) {
            console.log('failed  to get count');
        } else {
            return rows; // retun count
        }
    })
}

Note that probably returns a Promise you need to handle correctly.

about 4 years ago · Juan Pablo Isaza Relatório

0

Finally I got the required output by using Promise() in node js

Code:

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {      
    const Query = "SELECT * FROM t1";
    dbConn.query(Query,function(err,rows)     {
        if(err) {
            // write some code
        } else {
// call to promise
              getData().then(function (outputVal) {
                console.log(outputVal[0].Usr);
            }).catch(function () {
                // write error here
            });
        }
    
    });
});

// Promise code

function getData() {
    return new Promise(function (resolve, reject) {
        //  setTimeout(function () {
        const MQuery = "SELECT count(id) as Usr FROM t2";
        dbConn.query(MQuery , function (err, rows) {
            if (err) {
                reject();
            } else {
                resolve(rows);
            }
            // }, 1000);
        })
    })
}
about 4 years ago · Juan Pablo Isaza Relatório

0

A couple of things you should know:

  1. The functions declared outside routes will be executed first in stack once the server starts even though you haven't called the specific route yet. By the time you call this function, it already holds undefined or null depending on the code inside the functions.
  2. dbConn.query() is Promise. Which means it works synchronously.

if you need count of users, here is what you can do:

router.get('/', function(req, res, next) {      
    const usersQuery = "SELECT * FROM users";
    dbConn.query(usersQuery,function(err,rows)     {
        if(err) {
            console.log('this error',res);
        } else {
            let total= rows.length // you will get an array of users, therefore the number of users is equal to the length of the array
            console.log(total);
        }
        
   });
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda