I am trying check validations my instance on update with sequalize. Like documentation said
Validations are automatically run on create, update and save. You can also call validate() to manually validate an instance. validators
So if i pass a wrong name on update where i am using build in validation it is work but not how i expected.
Validation:
lastName: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notNull: {
msg: 'Please provide your last name'
},
len: {
args: [5, 20],
msg: 'Your last name should be between 5 and 20 characters'
}
}
},
Update method:
exports.updateUser = async (request, response) => {
try {
const userId = request.params.userId;
const user = await User.findByPk(userId);
console.log('Console log before update');
user.update(request.body);
console.log('consle log after update');
response.status(200).json({ status: ' Updated', data: { user } });
} catch (err) {
console.log(err);
response.status(400).json({ status: 'Bad Request ', message: err });
}
};
Unfortunately validation does not work. It seems to catch error after update method Error:
Executing (default): SELECT `userId`, `firstName`, `lastName`, `email`, `photo`, `password`, `passwordConfirm`, `createdAt`, `updatedAt` FROM `users` AS `user` WHERE `user`.`userId` = 'b31133f1-0be6-4b4f-9e07-651d42db1a3f';
Console log before update
consle log after update
Unhandled rejection SequelizeValidationError: Validation error: Your last name should be between 5 and 20 characters
I was searching for solution on lots of website and whole documentation but i don't find a them.
I have also my custom validation for password. This validation doesn`t run by default at all. So i try to use beforeUpdate hook. Like this:
{
hooks: {
beforeUpdate: function(user) {
const userToCheck = User.build(user.dataValues);
userToCheck.validate();
console.log('before');
user.validate();
}
}
}
or like this:
User.beforeUpdate(function(user) {
const userToCheck = User.build(user.dataValues);
userToCheck.validate();
//user.validate();
});
The user variable contains inside user previous data and data we want to update so i decide to build new instance(without saving) and run validation on it. However it work like before also. I throught that could be problem with asynchronous work and i don`t understand how it is work. I would be gratefull for help. Thank you