How to implement promises in nodejs? - javascript

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.

Related

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 send multiple query results from backend to frontend in node

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')
}
})

Node: run 2 sql queries at the same time

I have a simple api to communicate with my mobile app and i have some updates to do.
I want to make 2 updates at the same function (or th same route) but i dont know if its possible.
Here is the dboperation part:
async function updateCusto() {
try {
let pool = await sql.connect(config);
let updateCusto = await pool.request()
.input('input_parameter1', sql.Int, CodOS)
.input('input_parameter2', sql.Int, CodProduto)
.query("update osproduto set custounit=produto.precocusto, valorunitario=produto.precosugerido from OSProduto INNER JOIN Produto ON OSProduto.CodProduto = Produto.Codigo where codproduto=#input_parameter2 and codos=#input_parameter1")
.query("Update OSProduto set sub=qtde*valorunitario where codos=#input_parameter1") //the second one, doenst work
return updateCusto.recordsets;
}
catch (error) {
console.log(error);
throw error;
}
}
and here is the route part:
router.route("/updateCusto").post((request, response) => {
CodOS = request.body.CodOs;
CodProduto = request.body.CodProduto;
dboperations.updateCusto(CodOS, CodProduto).then(result => {
console.log(result);
response.json("Update ok!");
})
.catch(error => response.json({ error }))
})
How can i do this? Is there a way to run the 2 updates on the same operation? Or do i need to create another operation to use on the same route, after the first update is made (and if so, how can i do that?).
It's definitely possible, in fact I would do it as a transaction, this way if one of the queries fails a rollback would be made in order to preserve the state of your database.
Here are my suggestions:
Read about database transactions
Replace pure SQL with an ORM such as Sequelize or KnexJS, it will help you to prevent errors by making queries calling methods such as await OsProduto.update({ where: { id: 0 }}, newData);

Is there a way to find ids of two separate collections in one js function?

I have two collections in one database – "Neighborhood" and Restaurants".
I am trying to find the id of the neighborhood that I am currently in so that my "back" button on the restaurant.ejs page takes me back to the page with the path that contains that neighborhood's id.
I've tried:
findById({} ...
findById(id, ....
but I keep getting errors.
Here is my code – thinking I just need to add something in the ??? to fix:
neighborhood.get('restaurant/:id', (req, res) => {
Restaurant.findById(req.params.id, (err, restaurantInfo) => {
Neighborhood.findById(???, (err, foundNeighborhood) => {
res.render('restaurant.ejs', {
restaurant: restaurantInfo,
neighborhood: foundNeighborhood
})
})
})
});
If I understand your question correctly, either the restaurantInfo being returned will have some information about the neighborhood, as #paolo metioned above, or you would have to provide some way to look up the neighborhood in the req, maybe like this:
Restaurant.findById(req.params.id, (err, restaurantInfo) => {
Neighborhood.findById(req.params.neignborhoodId, (err, foundNeighborhood) => {
res.render('restaurant.ejs', {
restaurant: restaurantInfo,
neighborhood: foundNeighborhood
})
})
})
});
If you're getting errors, it would be good to check for errors in the callback like this:
Restaurant.findById(req.params.id, (err, restaurantInfo) => {
if (err) {
return err // you can add an error message here, too
} else {
Neighborhood.findById(req.params.neignborhoodId, (err, foundNeighborhood) => {
if (err) {
return err
}
res.render('restaurant.ejs', {
restaurant: restaurantInfo,
neighborhood: foundNeighborhood
}
})
})
})
});
I think the easiest, depending on your project, would be to include the neighborhood id as part of the restaurant info, then you could pass in the neighborhood id like this:
Neighborhood.findById(restaurantInfo.neighborhoodId, (err, foundNeighborhood) => {
If possible, you could use the neighborhood name to find the neighborhood id, since you said the restaurantInfo contains the neighborhood name. Or you could use a Neighborhood.findByName search instead of a findById.

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