[英]How to query postgres database for existing email
I am trying to create a very simple registration method on my project but I am having trouble figuring out how to stop postgres from adding in people with the same email. 我正在尝试在我的项目上创建一个非常简单的注册方法,但是在弄清楚如何阻止postgres添加具有相同电子邮件的人时遇到了麻烦。 I am using postgres and Node.js. 我正在使用postgres和Node.js。
I have an add function that I want to return false my postgres table already has a user with the email he/she tried using. 我有一个添加函数,我想返回false我的postgres表已经有一个用户使用他/她尝试使用的电子邮件。 I do the following: 我执行以下操作:
function checkExistingEmail(email, cb){
pg.connect(cstr, function(err, client, done){
if(err){
cb(err);
}
else{
var str = 'SELECT email from Swappers where email=$3';
client.query(str, function(err, result){
if(err){
cb(err);
}
else{
console.log(result.row.email);
if(result.row.email === undefined){
cb(false);
}
else{
cb(true);
}
}
});
}
});
}
Now when I display result.row.email to the console I get that it is undefined. 现在,当我向控制台显示result.row.email时,我知道它是未定义的。 Which is what I want for the first time user, so it should return true, and I should be able to add the user to the database and move on. 这是我第一次想要的用户,因此它应该返回true,并且我应该能够将用户添加到数据库中并继续前进。 But that is not the case. 但事实并非如此。
In a file I have called users.js I have the following route handler: 在一个名为users.js的文件中,我具有以下路由处理程序:
router.post('/authnewuser', function(req,res){
// Grab any messages being sent to use from redirect.
var authmessage = req.flash('auth') || '';
var name = req.body.username;
var password = req.body.password;
var email = req.body.email;
db.checkExistingEmail(email, function(data){
if(data === true)
console.log('success');
else
console.log('fail');
});
});
Now When I run this and try registering the functionality I want is not working. 现在,当我运行此程序并尝试注册我想要的功能时,它不起作用。 I was wondering if is has to go with my checkExistingEmail function and if I am using results.row.email correctly. 我想知道是否必须与我的checkExistingEmail函数一起使用,以及我是否正确使用了results.row.email。 Right now When I run this code I just keep getting that it has failed. 现在,当我运行此代码时,我一直在获取失败的信息。 Which is not what I want. 这不是我想要的。 it should be returning true for a new user with an email that has never been saved into the db before. 对于新用户,其电子邮件之前从未保存到数据库中,它应该返回true。
This is usually not the way to go with a database. 通常,这不是使用数据库的方法。 Checking first always requires two round-trips to the database. 首先检查总是需要两次往返数据库。 Instead, 代替,
Most inserts will just succeed--one round-trip to the database. 大多数插入操作将成功完成-数据库一次往返。 And you have to handle errors anyway--there's a lot of reasons an INSERT can fail. 无论如何,您都必须处理错误-INSERT失败的原因有很多。 So there's not a lot of additional code to write for this specific error. 因此,针对此特定错误,没有太多其他代码可编写。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.