Is there a better method of inserting a variable that is undefined as null using pg
const pg = require('pg');
a = a? a: null // hope to remove this line
b = b? b: null // hope to remove this line
c = c? c: null // hope to remove this line
client.query('INSERT INTO abc(a,b,c) VALUES($1,$2,$3)', [a,b,c], function(err, result) {
//do something here
})
so that don't have to check every variable and substitute "" for undefined before
Is there a better method of inserting a variable that is undefined as null using pg
const pg = require('pg');
a = a? a: null // hope to remove this line
b = b? b: null // hope to remove this line
c = c? c: null // hope to remove this line
client.query('INSERT INTO abc(a,b,c) VALUES($1,$2,$3)', [a,b,c], function(err, result) {
//do something here
})
so that don't have to check every variable and substitute "" for undefined before
Share Improve this question edited Jun 21, 2017 at 4:41 Stanley asked Jun 21, 2017 at 4:02 StanleyStanley 2,8166 gold badges27 silver badges45 bronze badges 5-
3
The code shown doesn't use
null
at all. Empty strings aren't null. – nnnnnn Commented Jun 21, 2017 at 4:06 -
2
do you realise this code would replace the number
0
and the booleanfalse
with''
as well? – Jaromanda X Commented Jun 21, 2017 at 4:08 -
2
if you're hoping to remove the 3 lines then will this work?
[ a || null, b || null, c || null]
– Samuel Toh Commented Jun 21, 2017 at 4:09 -
1
pg-promise does it automatically, both
undefined
andnull
are formatted asnull
. – vitaly-t Commented Jun 21, 2017 at 7:53 - thanks pg-promise seems to be pretty cool, can i check how does pg-promise handle partial updates? if u have SQL statement like UPDATE users SET name=$1, age = $2 WHERE id = $3 and values being ['a', undefined, 'id1'] does pg-promise update age column with null? or do a partial update by ignoring age? – Stanley Commented Jul 12, 2017 at 8:52
2 Answers
Reset to default 2you can define a undefined variable using || operator. Ex
var a ;
var b = a || null;
You can check the value with Boolean like
let test = null;
let b = `test is ${Boolean(test) == false ? "null" : ",'" + test + "'"}`;
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745228109a4617555.html
评论列表(0条)