0

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
        })
      })

    })
  }

1 Answer 1

1

You shouldnt do that in JavaScript, but rather in the database itself. Theres a neat little thing you can add to get this effect, its called "AUTO_INCREMENT". When you create a new Table, you can give it that keyword.

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

Cheers

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah I understand. However, what I am trying to do is each product already has a unique id. I just want to assign that id to the selected_product_id field. I changed the name in my code so it makes sense in terms of what I am trying to accomplish.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.