Richlewis
Richlewis

Reputation: 15374

Update multiple columns for a user - postgresql and nodejs

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

Upvotes: 1

Views: 545

Answers (1)

Ayush Gupta
Ayush Gupta

Reputation: 9295

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

Upvotes: 3

Related Questions