javascript - knex only add username if it doesn't already exist - Stack Overflow

I am using knex. Would like an easy way to check if the username exists in db. If it does, return error

I am using knex. Would like an easy way to check if the username exists in db. If it does, return error message ("username already exists"). If not then insert.

router.post('/register', (req, res) => {

const username = req.body.username;
const email = req.body.email;
const password = req.body.password;

  knex('users')
  .insert([{
    username: req.body.username,
    email: req.body.email,
    password: bcrypt.hashSync(req.body.password, 10)
   }]).then(()=>{})
 })

UPDATED Ok so i have the program working as expected. It inserts only if username and email don't exist in table. However I have two issues when I wrote this code.

Please note that I am fairly new with knex library and promises.

  1. Performance, my whole app has slowed down
  2. My if/else statement ends up always running both mands however, it never inserts into DB if email or username exist. However I always see the console.log even when it doesn't insert.

     const insertUser = knex('users')
    .returning('id')
    .insert([{
     username: req.body.username,
     email: req.body.email,
     password: bcrypt.hashSync(req.body.password, 10)
    }]).then(userNameValid => {console.log(userNameValid)})
    
    const validityCheck = knex.select("username")
    .from("users")
    .where("username", username)
    .andWhere("email", email)
    .then(userNametList => {
    console.log(userNametList)
    })
    
    if (!validityCheck){
    return insertUser;
    } else if (validityCheck !== null){
     return console.log('Username or email is already in use')
    }
    

I am using knex. Would like an easy way to check if the username exists in db. If it does, return error message ("username already exists"). If not then insert.

router.post('/register', (req, res) => {

const username = req.body.username;
const email = req.body.email;
const password = req.body.password;

  knex('users')
  .insert([{
    username: req.body.username,
    email: req.body.email,
    password: bcrypt.hashSync(req.body.password, 10)
   }]).then(()=>{})
 })

UPDATED Ok so i have the program working as expected. It inserts only if username and email don't exist in table. However I have two issues when I wrote this code.

Please note that I am fairly new with knex library and promises.

  1. Performance, my whole app has slowed down
  2. My if/else statement ends up always running both mands however, it never inserts into DB if email or username exist. However I always see the console.log even when it doesn't insert.

     const insertUser = knex('users')
    .returning('id')
    .insert([{
     username: req.body.username,
     email: req.body.email,
     password: bcrypt.hashSync(req.body.password, 10)
    }]).then(userNameValid => {console.log(userNameValid)})
    
    const validityCheck = knex.select("username")
    .from("users")
    .where("username", username)
    .andWhere("email", email)
    .then(userNametList => {
    console.log(userNametList)
    })
    
    if (!validityCheck){
    return insertUser;
    } else if (validityCheck !== null){
     return console.log('Username or email is already in use')
    }
    
Share Improve this question edited Sep 11, 2018 at 21:48 ashToronto asked Sep 8, 2018 at 0:39 ashTorontoashToronto 453 silver badges6 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

There's not a one shot knex function for that. If you have a unique constraint on the username (as you should) then you can do an insert and catch if it fails. The failure message would go in the catch handler.

Better practice would be to do a select first and only attempt the insert if it doesn't already exist otherwise return the error message before attempting the insert.

Updated answer for updated question: The insertUser promise is executed when it gets created so you are always inserting a user (and failing if it violates the unique constraint).

Your variable validityCheck is a promise, so !validityCheck will always be false.

What you want to do is create the insert user promise in the .then( ...) block of the validity check...

knex.select("username")
    .from("users")
    .where("username", username)
    .andWhere("email", email)
    .then(userNametList => {
        if (userNameList.length === 0) {
            return knex('users')
              .returning('id')
              .insert([{
                username: req.body.username,
                email: req.body.email,
                password: bcrypt.hashSync(req.body.password, 10);
              }])
              .then((newUserId) => {
                  console.log('inserted user', newUserId);
              });
        }
    console.log('not inserting user');
    return;
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745346474a4623570.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信