0

router.post('/university', function (req, res, next) {
 
   pg.connect(connectionString,function(err,client,done) {
      if(err){
          console.log("not able to get connection "+ err);
          res.status(400).send(err);
      } 

      client.query("select university_name from university where university_name = '"+req.body.university_name+"'",function(err,data)
      {
           if(data) {
             res.send({message:"exist"});
             
           }
           else
           {
             client.query("INSERT INTO university (_id, university_name, status) VALUES (nextval('university_id_seq'), '"+req.body.university_name+"', '"+req.body.status+"')", function(err, result) {
             done();
             if(err){
              console.log(err);
              res.status(400).send(err);
           }
           res.send({message : "successfully inserted"});
           
           });
           }
         });

it displays university_name as exist even it is not present on every entry, how to insert the record into PostgreSQL if does not exists?

Anusha S
  • 3
  • 2

1 Answers1

3

It depends on which DB driver you are using, anyway most common is that when SELECT query is executed, you will get result data even if records in the DB doesn't exists. Usually result object then has property rows which you should check.

In your case similar to this:

if(data.rows && data.rows.length > 0){
   // there is data in the DB
} else {
   // no data in the DB
}
Dario
  • 2,053
  • 21
  • 31
  • You're welcome. In addition you can read more about INSERT ... ON CONFLICT statement (usually known as UPSERT) and take care about possible SQL injection. – Dario Oct 09 '17 at 07:48