简体   繁体   中英

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. I am using postgres and 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. 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. 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. But that is not the case.

In a file I have called users.js I have the following route handler:

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. 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.

This is usually not the way to go with a database. Checking first always requires two round-trips to the database. Instead,

  • put a unique constraint on the "email" column,
  • just insert the data, and
  • handle the error you'll get with a duplicate email.

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. So there's not a lot of additional code to write for this specific error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM