简体   繁体   English

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

[英]in nodejs how to insert the record into PostgreSQL if it does not exist?

 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? 即使没有在每个条目上都显示,它也会显示university_name存在,如果不存在,如何将记录插入PostgreSQL?

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. 这取决于您使用的是哪个DB驱动程序,无论如何,最常见的是在执行SELECT查询时,即使数据库中的记录不存在,您也将获得结果数据。 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 运算符不存在:text = bigint with Nodejs and Postgresql - operator does not exist: text = bigint with Nodejs and Postgresql 如何使用nodejs在postgresql中插入值数组 - How to insert array of values in postgresql using nodejs 如果记录已存在或PDO MySQL插入查询中不存在该记录,如何生成JavaScript警报? - How do I generate a javascript alert if the record already exists OR if it does not exist in a PDO MySQL insert query? 如何使用 Nodejs 从文本文件读取数据并将数据插入 PostgreSQL? - How to read from text file and insert the data into PostgreSQL using Nodejs? 如何使用带有 nodejs 和 mongodb 的单一表单 texarea 插入多条记录 - How to insert multiple record using single form texarea with nodejs and mongodb postgreSQL错误:“约束不存在”(但确实存在……) - postgreSQL error: “constraint does not exist” (but it does exist…) 无法使用 pg-promise 在 NodeJS 中查询 PostgreSQL 数据库 - “关系不存在” - Unable to query PostgreSQL database in NodeJS using pg-promise - "relation does not exist" 插入输入(如果不存在) - Insert input if it does not exist 如何优雅地查询记录并创建它(如果它还不存在)? - How to elegantly query for a record and create it if it does not exist yet? 如果记录不存在则插入,如果存在则更新 - INSERT if record doesn't exist, UPDATE if exists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM