【问题标题】:Insert value in MySQL fields using node js使用节点 js 在 MySQL 字段中插入值
【发布时间】: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


    【解决方案1】:

    您不应该在 JavaScript 中这样做,而应该在数据库本身中这样做。你可以添加一个简洁的小东西来获得这种效果,它叫做“AUTO_INCREMENT”。当你创建一个新表时,你可以给它那个关键字。

    CREATE TABLE products (
        product_Id int NOT NULL AUTO_INCREMENT,
        quantity int,
        user_Id int,
        PRIMARY KEY (product_Id)
    );
    

    干杯

    【讨论】:

    • 是的,我明白了。但是,我想要做的是每个产品已经有一个唯一的 id。我只想将该 id 分配给 selected_product_id 字段。我在我的代码中更改了名称,因此它对我想要完成的工作有意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 2018-03-19
    • 1970-01-01
    • 2017-10-04
    • 2012-02-05
    • 1970-01-01
    • 2016-12-31
    相关资源
    最近更新 更多