最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to insert undefined value as null for pg node js - Stack Overflow

programmeradmin1浏览0评论

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 boolean false 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 and null are formatted as null. – 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
Add a ment  | 

2 Answers 2

Reset to default 2

you 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 + "'"}`;
发布评论

评论列表(0)

  1. 暂无评论