Why does the sequelize id auto-increment even without adding the data?

Asked

Viewed 13 times

0

Hello, I have a table that has[id, user, password, level] following these settings:

 id: {
   type:sequelize.INTEGER,
   primaryKey: true,
   autoIncrement: true,
   allowNull: false
 },
 user: {
   type: sequelize.STRING,
   allowNull: false,
   unique: true
 },
 password: {
   type: sequelize.TEXT,
   allowNull: false

 },
 level: {
   type: sequelize.STRING,
   allowNull: false
 }
})

Whenever I try to create a new user and it already exists, returns the error "Sequelizeuniqueconstrainainterror" , until then everything ok, because I had configured it, as shown in the code above. However, when I create a new user without returning this error, the "id" of the new user , in the database, appears as if the previous attempt had worked, example:

-I gave several clicks on the creation of a new user with the same name and returned several errors, however, after successfully creating a new one, the id was in this numbering.

13  william1    william15   admin
14  william william15   admin
34  willia  william15   admin
59  will    william15   admin

Code creating a new user:


rCreateUser.post('/', async (req: Request, res:Response)=> {
  const {user, password, level} = req.body
  try{
    const creatingUser: Model<any, any> = await Credencial_model.create({
      user:user,
      password:password,
      level: level
    })
    
    return res.json(creatingUser)
  }catch( Err) {
    console.log(Err.name)
    if(Err.name === 'SequelizeUniqueConstraintError'){
      res.status(409).json({info:'usuario já existe', error:true})
    }
  }
})
  • 1

    This is the normal behavior of Sequelize, or perhaps of the database itself. If you don’t want this behavior, the correct thing would be for you to do if to check whether the user already exists and launch the error or return a status. An alternative would be to use Transactions, but I think it would be too much for your case.

  • Okay, I thought about the IF alternative and I will implement it. My goal was to know if this is a bug or something, In this way, I thank you for your response.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.