Two client queries in that same function

Two client queries in that same function


I have a question about if it is right to do two client.queries one right after the other. I am trying to build a REST API. Example:

client.query("select waiters_id from waiters", function(err, result){
                         res.json({success: false, msg: "error"});
                     if(result.rows.length === 0){
                         res.json({success: false, msg: "error"});
                     } else{
                         if(results.rows[0].waiter_id === req.body.waitid){
                                 res.json({success: true, msg: "proceed"});
                         client.query("insert into waiters",function(err, result){
                              // MORE CODE

I am trying to check if there is a waiter in the waiters table, then insert some specific information into that waiter in that waiters table if there is a waiter. If there is a better way to do this please let me know. I don’t want to lose performance. Thanks

Problem courtesy of: user3192435


This question really has more to do with SQL then nodejs/express. SQL provides you with the ability to use if statements to make logical assertions about your results:

  "IF EXISTS (SELECT * FROM waiters WHERE waiters_id='SomeValue')
      UPDATE waiters SET (...) WHERE waiters_id='SomeValue'
      INSERT INTO waiters VALUES (...)
   SELECT * FROM waiters",
  function (err, result) {
     // do something with results here     

Which is essentially the same control logic you are trying to build with nodejs. Using the above would eliminate the need for another query.

Solution courtesy of: srquinn


Leave a Reply

Your email address will not be published. Required fields are marked *