In my MySQL database I have three fields (selected_product_id, quantity, user_id). Instead of manually entering a value for the selected_product_id body from postman, I want to run a MySQL query and pull product name and automatically assign the id of the product to the selected_product_id field.
//Controller.js file
addProduct: (req, res) =>{
const body = req.body;
let errors = {};
pool.query('SELECT name from products WHERE name = ?', [body.product_name], (error, results) => {
if(error){
console.log(error);
}
if(results.length === 0){
errors.message = 'Product not found'
}
else if(results.length > 0){
pool.query('SELECT id, name, maker from products WHERE name = ?', [body.product_name], (error, results)=>{
if(error){
console.log(error)
}
req.body.selected_product_id = //This is where I want to automatically assign the id value of the product
})
}
if(Object.keys(errors).length > 0){
return res.status(400).json(errors);
}
addUser(body, (err, results) =>{
if(err){
console.log(err);
return res.status(500).json({
success: false,
message: 'Database connection error'
})
}
return res.status(200).json({
success: true,
message: 'Request sent to [username]',
data: results
})
})
})
}