How to send multiple query results from backend to frontend in node - javascript

I am making a simple check-in and check-out system for employees. In the main panel I want to show the number of hours worked per day and in another field the weekly total.
I can now show the hours per day in a table, the problem comes when I have to show the total since I make that query to the database with another query.
With the following code I perform the query and perform a render in the index view using the EJS templates.:
router.get('/', (req, res) => {
const week = DateTime.now().weekNumber;
conexion.query('SELECT * FROM assistance WHERE week = ?', week, (error, results) => {
if(error){
throw error;
}else{
res.render('index', {results: results});
}
})
});
With this code I perform the query of the total hours. but I don't know how to show it in the same index view since it is a separate query from the first one:
conexion.query('SELECT time_format(SUM(TIMEDIFF(a.exit, a.entry)), "%H:%i") AS hours from assistance a WHERE a.week = ?', week, (error, results) => {
if(error){
throw error;
}else{
return('index', {totalHours: results});
}
})
In this way I am trying to receive the information in the index view with EJS:
<div>
<div>Total hours:<%= totalHours%></div>
</div>

Use try/catch async-await, then just do both queries.
router.get('/', async(req, res) => {
const week = DateTime.now().weekNumber
try {
// query 1
const totalHours = await conexion.query('SELECT time_format(SUM(TIMEDIFF(a.exit, a.entry)), "%H:%i") AS hours from assistance a WHERE a.week = ?', week)
// query 2
const results = await conexion.query('SELECT * FROM assistance WHERE week = ?', week)
res.render('index', {
totalHours,
results
})
} catch {
res.render('error-page')
}
})

Related

How to convert MYSQL Timestamp to CST time with Javascript?

If someone could help me with this I´d appreciate it!
I need to convert MYSQL Timestamp 2022-09-14T05:08:32.000Z to my local time (Central Standard Time) and then be able to pass that result to EJS. I am passing the data to my EJS view with this route, but not sure how to convert this timestamp before passing it to EJS.
This screenshot shows the 'rows' values which are being passed to EJS.
rutas.get('/historial', loggedIn, async (req, res, next) => {
await pool.query('SELECT * FROM historial WHERE id = ? AND calidaddeltrade = ? OR calidaddeltrade = ?', [req.user.id, 'Excelente', 'Buena'], function (err, rows, fields) {
if (err) { throw err };
res.render('./historial', { rows: rows});
console.log(rows);
})
});
Does anyone know how could I do this with Javascript? Thanks!!

Unknown column in where clause in NextJS API

I'm writing an API which would fetch data from a MySQL table based on a category. The code currently looks like this.
import { sql_query } from "../../../lib/db"
export default async function handler(req, res) {
var category = 'Starters'
if (req.method === 'GET') {
try {
const results = await sql_query({
query_string: `SELECT * FROM products WHERE category = ${category}`
})
return res.status(200).json(results)
} catch (error) {
res.status(500).json({ message: error.message })
}
}
}
This isn't going through for some reason and instead, I see this error message
{"message":"ER_BAD_FIELD_ERROR: Unknown column 'Starters' in 'where
clause'"}
From what I know, my MySQL query is fine because it works okay in PHPMyAdmin. Can anyone point out what I'm doing wrong here?
The error indicates the parameter is being injected and used in the context of a column name, you need to contain it within quotes:
`SELECT * FROM products WHERE category = '${category}'`

How to implement promises in nodejs?

I made this project based on a YT tutorial but adding some extra features
image
the problem I have is the following, this is the code that is used to show the data of the database
controller.list = (req, res) => {
req.getConnection((err, conn) => {
conn.query("SELECT * FROM usuarios ", (err, usuarios) => {
if(err){
res.json(err)
}
res.render("usuarios", {
data: usuarios
})
})
})
}
but I don't know how to modify it so that in the part that says "usado" it shows me the number of times that the "Codigo" is repeated. I know that with a MySQL query similar to this one 'SELECT COUNT(*) AS namesCount FROM names WHERE age = ?' I can show the number of times it repeats, but I don't know how to implement this in the controller, I know I can do it with promises but I don't know how to modify the code to implement it.

How do I get all objects with a specific start date

I'm trying to use a date parameter that comes in through the request and return all objects that have that date. I do not want to look at the time stamp, just the year, month, day.
The following in the controller file of mongoose finds dates that match a specific day:
export const getBookingByDate = (req, res) => {
Booking.find({start: {$gt: req.params.bookingDate}}, (err, booking) => {
if(err){
res.send(err);
}
res.json(booking);
})
}

pass a json result of a mysql query as a param to my ejs in Node/express

I have a query to get all my users. I have been doing res.json(rows) to display to screen until now. Now I want to pass the object obtain from the query to a ejs file and display it. If I do like my code below, the object pass is a string and I can´t iterate or obtain the fields.
What is the best way to achive what I´m trying to do?
router.get("/users", (req, res) => {
const connection = getConnection();
const newLocal = "SELECT * FROM client";
connection.query(newLocal,(err, rows, fields) => {
if (err) {
console.log("Error "+err);
res.sendStatus(500);
return;
}
// res.json(rows);
res.render("users.ejs", {users: JSON.stringify(rows)});
});
});
It's because you're turning your Array rows into a String. Remove JSON.stringify

Categories

Resources