I'm new to Node, APIs and SQL and I hit a wall. I'm using pg-promise prepared statements and I'm trying to use a sorted parameter with the ORDERED BY command to do the usual sorting of the results but it doesn't work as the always come in ordered the same.
If I us the parameter's name directly it does work instead, can you see what am I doing wrong with my query?
As usual many thanks for your time and help.
This is my method:
if (city, region, country, category, minPrice, maxPrice, orderedBy, sorted) {
if (sorted == 'asc') {
await db.any({
name: 'get-city-category-price-range-ordered-by-asc-products',
// text: 'SELECT * FROM products WHERE city = $1 AND region = $2 AND country = $3 AND category = $4 AND price >= $5 AND price <= $6 ORDER BY price ASC', // working
text: 'SELECT * FROM products WHERE city = $1 AND region = $2 AND country = $3 AND category = $4 AND price >= $5 AND price <= $6 ORDER BY $7 ASC', // not working
values: [city, region, country, category, minPrice, maxPrice, orderedBy]
})
.then(result => {
console.log('get-city-category-price-range-ordered-by-asc-products:', result);
if (result.length > 0) {
res.status(200).send({
data: result
});
}
else {
res.status(404).send({
error: 'No product found.'
});
}
})
.catch(function (error) {
console.log('get-city-category-price-range-ordered-by-asc-products error:', error);
});
} else if (sorted == 'desc') {
await db.any({
name: 'get-city-category-price-range-ordered-by-desc-products',
// text: 'SELECT * FROM products WHERE city = $1 AND region = $2 AND country = $3 AND category = $4 AND price >= $5 AND price <= $6 ORDER BY price DESC', // working
text: 'SELECT * FROM products WHERE city = $1 AND region = $2 AND country = $3 AND category = $4 AND price >= $5 AND price <= $6 ORDER BY $7 DESC', // not working
values: [city, region, country, category, minPrice, maxPrice, orderedBy]
})
.then(result => {
console.log('get-city-category-price-range-ordered-by-desc-products:', result);
if (result.length > 0) {
res.status(200).send({
data: result
});
}
else {
res.status(404).send({
error: 'No product found.'
});
}
})
.catch(function (error) {
console.log('get-city-category-price-range-ordered-by-desc-products error:', error);
});
}
}