最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何在Node.js和Handlebars中使用JSON对象值更新数据库

网站源码admin21浏览0评论

如何在Node.js和Handlebars中使用JSON对象值更新数据库

如何在Node.js和Handlebars中使用JSON对象值更新数据库

我想使用NodeJ和Handlebars中的JSON对象值更新MySQL数据库。我已经成功创建了JSON。该JSON仅包含idupdated_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

希望这会有所帮助,请在下面添加问题以进行澄清。

发布评论

评论列表(0)

  1. 暂无评论