0

At this moment, in part of the code, I want to display the result of the number of records in a table, but I get an error message [Object Object] I have seen some similar questions but they have not helped me, I do not know if someone can correct me where I'm making the mistake.

app.js

app.get('/dashboard', (req, res) =>{
    connection.query('SELECT COUNT(*) FROM dimensions', function(error, resultsd) {
        if (error) {
            console.log(error);
            res.sendStatus(500);
            return;
        }
        connection.query('SELECT COUNT(*) FROM categorias',function(error, resultsc){
            if (error){
                console.log(error);
                res.sendStatus(500);
                return;
            }
            connection.query('SELECT COUNT(*) FROM subcategoria',function(error, resultss){
                if (error){
                    console.log(error);
                    res.sendStatus(500);
                    return;
                }
                res.render('./dashboard', {
                    resultsd:resultsd,
                    resultsc:resultsc,
                    resultss:resultss
                });
            })
        })

    })
})

Y en views/dashboard.ejs

<div class="container-fluid py-4" style="width: 100%; margin-left: 6%; margin-right: 5%;
       padding-right: 8%; margin-top: 2%;" >
        <div class="row" style="text-align:right;">
          <div class="col-xl-3 col-sm-6 mb-xl-0 mb-4">
            <div class="card">
              <div class="card-header p-3 pt-2">
                <div class="icon icon-lg icon-shape bg-gradient-dark shadow-dark text-center border-radius-xl mt-n4 position-absolute">
                    <i class="fa-solid fa-book"></i>
                </div>
                <div class="text-right">
                  <p class="text-sm mb-0 text-capitalize">Dimensiones</p>
                  <h4 class="text-right-mb-0"><%= resultsd %></h4>
                </div>
              </div>
            </div>
          </div>
          <div class="col-xl-3 col-sm-6 mb-xl-0 mb-4">
            <div class="card">
              <div class="card-header p-3 pt-2">
                <div class="icon icon-lg icon-shape bg-gradient-primary shadow-primary text-center border-radius-xl mt-n4 position-absolute">
                    <i class="fa-solid fa-book-open"></i>
                </div>
                <div class="text-right">
                  <p class="text-sm mb-0 text-capitalize">Categorias</p>
                  <h4 class="text-right-mb-0"><%= resultsc %></h4>
                </div>
              </div>
            </div>
          </div>
          <div class="col-xl-3 col-sm-6 mb-xl-0 mb-4">
            <div class="card">
              <div class="card-header p-3 pt-2" >
                <div class="icon icon-lg icon-shape bg-gradient-success shadow-success text-center border-radius-xl mt-n4 position-absolute">
                    <i class="fa-solid fa-file"></i>
                  </div>
                <div class="text-right">
                  <p class="text-sm mb-0 text-capitalize">Subcategorias</p>
                  <h4 class="text-right-mb-0"><%= resultss %></h4>
                </div>
              </div>
            </div>
          </div>
          <div class="col-xl-3 col-sm-6">
            <div class="card">
              <div class="card-header p-3 pt-2">
                <div class="icon icon-lg icon-shape bg-gradient-info shadow-info text-center border-radius-xl mt-n4 position-absolute">
                    <i class="fa-solid fa-user"></i>
                </div>
                <div class="text-right">
                  <p class="text-sm mb-0 text-capitalize">Usuarios</p>
                  <h4 class="text-right-mb-0">$103,430</h4>
                </div>
              </div>
            </div>
          </div>
        </div>  
    </div>

I am currently managing MYSQL with Phpmyadmin, rendering with NodeJS (EJS).

Also try the following examples;

res.render('./dashboard', {
                    resultsd:resultsd[0],
                    resultsc:resultsc[0].rows,
                    resultss:resultss[0].count
                });

The messages appear more or less like this but do not generate any errors in the log. Error

Its my console log;

res.render('./dashboard', {
                    resultsd:resultsd,
                    resultsc:resultsc,
                    resultss:resultss
                });
                    console.log("🚀 ~ file: app.js ~ line 468 ~ q2 ~ resultss", resultss)
                    console.log("🚀 ~ file: app.js ~ line 468 ~ q2 ~ resultsc", resultsc)
                    console.log("🚀 ~ file: app.js ~ line 468 ~ q2 ~ resultsd", resultsd)
            })

Console log response

🚀 ~ file: app.js ~ line 468 ~ q2 ~ resultss [ RowDataPacket { 'COUNT(*)': 5 } ]
🚀 ~ file: app.js ~ line 468 ~ q2 ~ resultsc [ RowDataPacket { 'COUNT(*)': 4 } ]
🚀 ~ file: app.js ~ line 468 ~ q2 ~ resultsd [ RowDataPacket { 'COUNT(*)': 5 } ]

And thats my app.js / Configure conection

const express = require('express');
const app = express();
var bodyParser = require('body-parser');
const dotenv = require('dotenv');
const bcryptjs = require('bcryptjs')
const session = require('express-session');
const logger = require('./logger');
const morgan = require('morgan');

//Logs

logger.error('Error log example');
logger.warn('Warn log example');
logger.info('Info log example');


app.use(morgan('tiny', { stream: logger.stream }));

//Conexion A SERVIDOR

app.listen(5600,(req, res) =>{
    console.log('SERVER RUNING IN http://127.0.0.1:5600/ingresar');
})

//Resultados de Variables
//Envio de variables de base de datos
dotenv.config({path:'./env/.env'});


//Uso de urlencoded - BodyParser
app.use(bodyParser.urlencoded({
    extended: false
}));

app.use(bodyParser.json());

//Envio directorio EJS a Publico
var path = require ('path');
app.use(express.static(path.join(__dirname + '/public')));


app.set('views', __dirname + "/views/");
app.set('view engine', 'ejs');



//Express-Sesion

app.use(session({
    secret:'secret',
    resave: true,
    saveUninitialized:true
}))

//- VARIABLES DATA BASE - Invocar al modulo de conexion
const connection = require('./database/db');
const {response, application} = require('express');

7
  • 1
    Can you edit in the full error message you are getting, and also see if you can edit the code down to a minimum reproducible sample? This will make getting answers much easier Commented Nov 1, 2022 at 23:49
  • @Dakeyras Sorry, I didn't think about it, I just edited my question. Commented Nov 2, 2022 at 0:00
  • @Dakeyras I don't get any specific error in console log or similar, I only get Object Object, as if the value could not be adjusted. Commented Nov 2, 2022 at 0:02
  • 2
    Where is the connection coming from? Which package are you using to connect to the database? And also have you tried using console.log() or something to look at the internals of the object, maybe in combination with JSON.stringify() if necessary? Commented Nov 2, 2022 at 0:08
  • Yes, of course it is. It comes from these files, I'll edit my question again so you can see it better, but it is as follows Commented Nov 2, 2022 at 0:13

1 Answer 1

2

What it looks like is happening here is that the objects themselves are being passed to views/dashboard.ejs, where you just want the numbers. You can see in the print statements that resultss is [ RowDataPacket { 'COUNT(*)': 5 } ]. So in order to pass that to the template, you need to access resultss[0]['COUNT(*)'], which will equal 5. That's the COUNT(*) element of the first element of the array, resultss. For that whole section, what it looks like you want is the following:

res.render('./dashboard', {
  resultsd:resultsd[0]['COUNT(*)'],
  resultsc:resultsc[0]['COUNT(*)'],
  resultss:resultss[0]['COUNT(*)']
});
Sign up to request clarification or add additional context in comments.

2 Comments

Muchisimas gracias! Si era eso
@SofiaBlancoSanchez You can update your query to SELECT COUNT(*) AS COLUMN_NAME and then access via resultsd:resultsd[0]['COLUMN_NAME'] which may be more readable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.