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); }); 
3
  • Just use a normal UPDATE query. Like UPDATE table SET column = value WHERE x = y Commented Feb 22, 2020 at 2:44
  • Your other columns will remain untouched Commented Feb 22, 2020 at 2:45
  • @iJamesPHP2 i Updated my question with code , can u please check and solve it ? Commented Feb 22, 2020 at 2:53

1 Answer 1

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)); 
Sign up to request clarification or add additional context in comments.

6 Comments

There was an error in my code, I didn't see you are using req.body and not just req to access the columns, please use my latest edit
@tafhim Oh, I've just realised your query is hardcoded, you'd then need to build the query dynamically from the array in a loop
what is the query? =)
confused ... sry xD
can we just make two variables like : column : requested col```` and value : req.body ``` ? this simple?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.