【发布时间】:2020-10-03 01:57:06
【问题描述】:
在我的 MySQL 数据库中,我有三个字段(selected_product_id、数量、user_id)。我不想从邮递员手动输入 selected_product_id 正文的值,而是想运行 MySQL 查询并提取产品名称并自动将产品的 id 分配给 selected_product_id 字段。
//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
})
})
})
}
【问题讨论】:
标签: javascript mysql node.js api rest