在nodejs中,如果它不存在,如何将记录插入PostgreSQL?

时间:2017-10-09 07:12:35

标签: javascript node.js postgresql



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"});
           
           });
           }
         });




它显示university_name存在,即使它不存在于每个条目, 如果不存在,如何将记录插入PostgreSQL?

1 个答案:

答案 0 :(得分:3)

这取决于您使用的是哪个数据库驱动程序,最常见的是,当执行SELECT查询时,即使数据库中的记录不存在,您也将获得结果数据。通常结果对象具有您应该检查的属性行。

在你的情况下类似于:

if(data.rows && data.rows.length > 0){
   // there is data in the DB
} else {
   // no data in the DB
}