Matthew
Matthew

Reputation: 271

Getting sequelize attribute notNull violation in my create controller due to variable name being different from column name

Im trying to add users into my database using bcrypt so I can has their passwords, but when I set the req.body to the bcrypt variable I get a notNull Violation: Users.user_password cannot be null.

This is my model I used to define my users table

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Users extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  };
  Users.init({
    user_id:{ 
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
    },
    user_name:{ 
      type: DataTypes.STRING,
      allowNull: false
    },
    user_email:{ 
      type: DataTypes.STRING,
      allowNull: false
    },
    user_password:{ 
      type: DataTypes.STRING,
      allowNull: false
    },
  }, {
    sequelize,
    timestamps: false,
    modelName: 'Users',
    tableName: 'users'
  });
  return Users;
};

This is the controller I'm using to add a new user. At the bottom when I pass in the bcryptPassword variable instead of the user_password thats deconstructed at the top, I get the notNull Violation. But if I dont pass in the bcryptPassword variable I can create a new user. Does anyone know why this is happening? Is there a way to config the model so I can use any vairable? Any help would be greatly appreciated!

Thanks!

const { Users } = require('../models');
const bcrypt = require('bcrypt');

module.exports = {
    
    createUser: async(req, res) => {
        const { user_name, user_email, user_password } = req.body;

        try {
            
            const salt = await bcrypt.genSalt(10);

            const bcryptPassword = await bcrypt.hash(user_password, salt)
           
            const newUser = await Users.create({ user_name, user_email, bcryptPassword });

            return res.json(newUser);

        } catch (error) {
           
            console.error(error.message);
            return res.status(500).json(error);
        }
    }
}

Upvotes: 1

Views: 762

Answers (1)

Matthew
Matthew

Reputation: 271

I found a viable answer while searching through the sequelize documentation. https://sequelize.org/master/manual/getters-setters-virtuals.html

I used the set() function in my user_password field and that worked. Every time I created a new user the password was hashed in the database using bcrypt.

Here is the modified model code. Changes are marked by asterics.

'use strict';
*****const bcrypt = require('bcrypt');*****
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Users extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  };
  Users.init({
    user_id:{ 
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
    },
    user_name:{ 
      type: DataTypes.STRING,
      allowNull: false
    },
    user_email:{ 
      type: DataTypes.STRING,
      allowNull: false
    },
    user_password:{ 
      type: DataTypes.STRING,
      allowNull: false,
      *****set(value) {
        const hash = bcrypt.hashSync(value, 10);
        this.setDataValue('user_password', hash);
      }*****
    },
  }, {
    sequelize,
    timestamps: false,
    modelName: 'Users',
    tableName: 'users',
  });
  return Users;
};

Upvotes: 1

Related Questions