对象值更新数据库"/>
如何在Node.js和Handlebars中使用JSON对象值更新数据库
我想使用NodeJ和Handlebars中的JSON对象值更新MySQL数据库。我已经成功创建了JSON。该JSON仅包含id
和updated_order
。现在,我必须使用updated_order
值,并使用where子句的id
值对其进行更新。
我对NodeJ完全陌生。我要求您提供帮助和建议以完成此任务。
Products.handlerbars->
<form id="skuFormorders" method="post" action="/products/orders">
<button id="update_order" type="button" class="btn btn-outline-success btn-sm" style="background-color:white" onclick="xxx.prepUpdateOrder();">Yes</button>
</form>
app.js->
app.post('/products/orders', products.updateOrders);
在products.handlebars中创建JSON对象->
xxx.getUpdateOrderJson = function(){
var jsonObj = [];
var id = '';
var existing_order = '';
var updated_order= '';
var updated_row='';
jQuery("table tbody tr").each(function (index, value) {
id = $(value).find('.orderid').data("value");
existing_order = $(value).find('.exsorder').data("value");
updated_order = (index+1);
updated_row = {}
if(existing_order != updated_order){
updated_row ["id"] = id;
updated_row ["updated_order"] = updated_order;
jsonObj.push(updated_row);
}
});
console.log(JSON.stringify(jsonObj));
};
xxx.prepUpdateOrder = async function (e) {
$('#upOrders').val(xxx.getUpdateOrderJson());
document.getElementById('skuFormorders').submit();
});
Products.js->
exports.updateOrders = async (req, res) => {
console.log('wdhwidhwidhw');
try {
utils.log(JSON.stringify(req.body.data,null,4));
const connection = await mysql.createConnection(config.mysql.credentials);
const upOrders = req.body.data;
for (let element of upOrders) {
let id = element.id;
let updated_order = element.updated_order;
const query = `update pdb_product set orders = '${updated_order}' where id = '${id}' `;
await connection.query(query);
};
res.send('success');
} catch (e) {
utils.error500(req, res, e.message);
}
};
表结构:
CREATE TABLE `pdb_product` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`product_code` varchar(20) NOT NULL,
`description` varchar(255) DEFAULT NULL,
`active` tinyint(4) DEFAULT '1',
`third_party` tinyint(4) DEFAULT '0',
`orders` int(10) NOT NULL,
`note` varchar(45) DEFAULT NULL,
`cost_price` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
UNIQUE KEY `product_id_UNIQUE` (`product_code`)
[C0的输出->
console.log(JSON.stringify(jsonObj));
[{"id":2,"updated_order":1},{"id":3,"updated_order":2},{"id":1,"updated_order":3}]
在控制台中成功打印。请帮我解决这个问题。谢谢。
确定,下面是简化的工作版本。针对您提供的jsonObj
和变量schema
定义的有效负载进行了测试。为了便于理解,所有内容都已移动到一个文件中,在您的项目中,该文件很可能是jsonObj
。随附说明,并在需要时提供说明:
Products.js
Products.js
希望这会有所帮助,请在下面添加问题以进行澄清。
更多推荐
如何在Node.js和Handlebars中使用JSON对象值更新数据库
发布评论