Saturday 20 May 2017

Multiple queries/UPSERT in node postgres

Is there anything wrong with making multiple queries in one connection and ajax call?For exampleapp.post("/queries", function(req, resp) { pg.connect(dbURL, function(err, client, done) { client.query("SELECT ... ", function(err, result) { done(); }); client.query("INSERT INTO...", function(err, result) { done(); }); }); }); Now, specifically for what I am trying to accomplish. I am trying to UPSERT. Basically, SELECT from a table, if result is equal to 1, UPDATE, otherwise, INSERT. Here is what I have in mind.app.post("/upsert", function(req, resp) { pg.connect(dbURL, function(err, client, done) { client.query("SELECT ...", function(err, result) { done(); if (result.rows == 1) { client.query("UPDATE...", function(err, result) { done(); }); } else if (result.rows == 0) { client.query("INSERT...", function(err, result) { done(); }); } }); }); }); Is there a way to do this in one query?

Submitted May 21, 2017 at 02:40AM by eggtart_prince

No comments:

Post a Comment