1

I appreciate that this questions has been covered many times but cannot seem to get it to work for my scenario, I'm just not getting the syntax nor implementation right.

Right now I have a very simple update method that updates 1 column, finding that user by it's id

User.update = (id, value) => {
  pool.query('UPDATE users SET membership_expiry_date = $2 where id = $1', [id, value], (err) => {
    if (err) {
      return console.error(err);
    }
    return console.log('User Updated');
  });
};

await User.update(req.body.user_id, "value");

I have multiple columns that I would like to update and not sure how to set this up. Each time I update i could have a different number of columns to update, depending on what information is being updated

1 Answer 1

3

You can pass the columns you want to pass as an object and build the query dynamically.

User.update = (id, values) => {
      let columns = Object.keys(values);
      let params = [id];
      let query = "UPDATE users SET ";
      for(let i = 0; i < columns.length; i++) {
        query = `${query}${columns[i]} = $${params.length + 1},`
        params.push(values[columns[i]]);
      }
      query = `${query.substring(0, query.length-1)} WHERE id = $1`
      console.log(query);
      console.log(params)
    };

await User.update("req.body.user_id", {columnToUpdate: "newValue"});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer, I will give this a go

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.