-2

I have been on this for a good few hours.

I have the below function which reads from a table in my postgres db. It works as expected if there is stored strings in a column.

I can't get the 'else if' statement to work when there is no string in a field. To test this out I have a completely empty column under brand_code and its still executing the 'else' statement.

Now, I know why. There are 3 rows in the table. When I change the else if to === 3, it works as I'd like.

What code do I need to make the 'else if' statement work if the field is empty? (I plan to expand the SELECT statement later).

readCodes: function(callback) {
      var pool = new pg.Pool(config.PG_CONFIG);
      pool.connect(function(err, client, done) {
          if (err) {
              return console.error('Error acquiring client', err.stack);
          }
          client
              .query(
                  'SELECT brand_code FROM public.voucher_codes',
                  function(err, result) {
                    if (err) {
                        console.log(err);
                        callback('');
                      } else if (result.rows.length === 0 ) {
                        console.log(result);
                        callback('');
                      } else {
                          let codes = [];
                          for (let i = 0; i < result.rows.length; i++) {
                              codes.push(result.rows[i]['brand_code']);
                          }
                          callback(codes);
                      };
                  });

      });
    }

}

Really struggled with this all day so any help is appreciated.

I am still learning. Prior to last week, I have never coded so apologies if this is amateur hour.

1 Answers1

0

The problem here is that you are checking if it has returned rows or not, what you need instead is to check in each row if the field is empty

I suggest using underscore for iterating over each row:

_.each(result.rows,function(element, index){
  if(element['brand_code'].length != 0){
     codes.push(element['brand_code'])
  }else{
     console.log('empty field @ results['+index+']')
  }
})

CODE :

readCodes: function(callback) {
  var pool = new pg.Pool(config.PG_CONFIG);
  pool.connect(function(err, client, done) {
  if(err){return console.error('Error acquiring client',err.stack);}
  client.query(
    'SELECT brand_code FROM public.voucher_codes',
    function(err, result) {
     if (err){console.log('[!] Error:',err); callback('');} 
     else if(result.rows.length == 0 ){
       console.log('[!] Error:','No rows returned!');
       callback('');
     } else {
       let codes = [];
       _.each(result.rows,function(element, index){
        console.log(element , index)
        if(element['brand_code'].length != 0){
          codes.push(element['brand_code'])
        }else{
          console.log('empty field @ results['+index+']')
        }
       })                        
       callback(codes);
     }
    });
  });
}
EMX
  • 6,066
  • 1
  • 25
  • 32
  • That sounds to be exactly the issue, thank you. Will is code replace whats after the 'else if' and before the 'else' statement? Im still learning node.js / javascript. – Hikertommy Aug 24 '17 at 20:53
  • @Hikertommy, I added the working function in the answer, its a complete replacement for the function that is used in your current query. remember to include underscore `const _ = require('underscore')` and `npm install underscore` – EMX Aug 24 '17 at 20:59
  • @EMX why install one more dependency if js natively supports `Array.forEach`? – alexmac Aug 24 '17 at 21:01
  • @alexmac because it is a good dependency (opinion based), with many utilities that can come handy, specially useful if he is a beginner **wanting** to learn. [+ cleaner code] , Its good you point ``Array.forEach`` , [check the benchmarks](https://jsperf.com/jquery-each-vs-each-vs-for-loop/3) :) – EMX Aug 24 '17 at 21:03
  • 1
    I don't think that beginner wants to study one more unknown area. He needs to understand basic things. – alexmac Aug 24 '17 at 21:07
  • @alexmac That is your opinion, and its good. But this is up to the OP. I'm sure he can perfectly learn how to use simple yet powerfull `_` . **Knowledge can fill a room, but takes up no space**. – EMX Aug 24 '17 at 21:12
  • Thanks for your help @EMX. I tried the above but I get "module.js:471 throw err; ^Error: Cannot find module 'underscore'" I installed npm install underscore from terminal which gives me success (1.8.3) but its throwing the error still. – Hikertommy Aug 24 '17 at 21:16
  • @Hikertommy Thats because you are missing what I mentioned earlier : include underscore `const _ = require('underscore')` as a global variable for example and remember to do `npm install underscore` from a terminal to download the library. If this has solved your question. remember to close the question by marking it as solved. :) – EMX Aug 24 '17 at 21:18
  • @EMX. I did see that, I added `const _ = require('underscore'); ` to my global variable list and did `npm install underscore` (I can see the underscore folder under node_modules). Pushed the git to heroku but still throwing `State changed from starting to crashed 2017-08-24T21:23:46.727272+00:00 app[web.1]: module.js:471 2017-08-24T21:23:46.727288+00:00 app[web.1]: throw err; 2017-08-24T21:23:46.727289+00:00 app[web.1]: ^ 2017-08-24T21:23:46.727290+00:00 app[web.1]: 2017-08-24T21:23:46.727290+00:00 app[web.1]: Error: Cannot find module 'underscore'` – Hikertommy Aug 24 '17 at 21:28
  • @Hikertommy is it in your `package.json`? If you dont have the last release of npm you have to do `npm install underscore --save` to add it to your `package.json` – EMX Aug 24 '17 at 21:34
  • That did the trick. But another err `_.each(results.rows,function(element, index){ 2017-08-24T21:37:46.072091+00:00 app[web.1]: ^ 2017-08-24T21:37:46.072092+00:00 app[web.1]: 2017-08-24T21:37:46.072093+00:00 app[web.1]: ReferenceError: results is not defined` This makes sense as the function was never to handle this. It was original to pull all options from a column in a table and the original if (err) was to capture any issues. Ive since tried to expand it and failed miserably. I think I need to learn more :( – Hikertommy Aug 24 '17 at 21:41
  • @Hikertommy, I edited the answer, check that code, does it look like yours? – EMX Aug 24 '17 at 21:48
  • I noticed it was `results` so changed to `result`. This then threw the err `if(element['brand_code'].length != 0){ 2017-08-24T21:46:51.609196+00:00 app[web.1]: ^ 2017-08-24T21:46:51.609196+00:00 app[web.1]: 2017-08-24T21:46:51.609197+00:00 app[web.1]: TypeError: Cannot read property 'length' of null` – Hikertommy Aug 24 '17 at 21:48
  • @Hiketommy `console.log(element , index)` inside the each so you can see what each iteration contains, use `console.log()` to understand whats going on behind the scenes, but you should remove the console.log() it for production (once your code is working) – EMX Aug 24 '17 at 21:51
  • I got it working but its doing the same thing. I removed the .length and changed to `!= null` to get it working. Even though its now identifying empty fields, it still callsback to a success message. `query result [object Object] 2017-08-24T22:10:16.836922+00:00 app[web.1]: rows: 1 2017-08-24T22:10:16.840848+00:00 app[web.1]: empty field @ result[0] 2017-08-24T22:10:16.843452+00:00 app[web.1]: empty field @ result[1] 2017-08-24T22:10:16.843499+00:00 app[web.1]: empty field @ result[2]` Maybe I need to rethink the whole function in a different way. – Hikertommy Aug 24 '17 at 22:17
  • @Hikertommy then add an extra check after the each has finished to check if there has been any brand_name included in the array, so depending in that you do a success callback or not :) – EMX Aug 24 '17 at 22:39