1

imagine we have 10 columns in a table, and we want to update our table columns with input just 1 value and doesn't change remain values.

So just our new value will update and unnecessary values will not be Null ...?

i ASK this because i'm using This code and i want to send put requests depends on my edited content ...

i'm using this query to put request from body(react) into node postgres ...

router.put("/user/:nationalcode", (req, res) => {
  const cols = [
    req.body.nationalcode,
    req.body.stockcode,
    req.body.firstname,
    req.body.lastname,
    req.body.isenable,
    req.body.isonline,
    req.body.detail,
    req.body.birthdate,
    req.body.archive,
    req.body.offlineusername
  ];

  db.query(
    `UPDATE users SET nationalcode=$1, stockcode=$2, firstname=$3, lastname=$4, isenable=$5, isonline=$6, detail=$7, birthdate=$8, archive=$9, offlineusername = $10 WHERE nationalcode = ${req.params.nationalcode}`,
    cols,
    function(err, result) {
      if (err) {
        console.log("Error. Updating : %s ", err);
      }
    }
  );
  console.log(req.body);
});
tafhim
  • 123
  • 9

1 Answers1

0

You want to strip out null values from your req.body object, use this function to strip it before you build the cols array:

function strip(obj) {
    for (var prop in obj) {
        if (obj[prop] === null || obj[prop] === undefined) {
            delete obj[prop];
        }
    }
}

So, define the function and use this as the first line of your code:

var cols = Object.values(strip(req.body));
iJamesPHP2
  • 524
  • 4
  • 13