Last active
December 19, 2015 10:59
-
-
Save ppmathis/5944395 to your computer and use it in GitHub Desktop.
[sequelize] validation gets messed up when updating an model instance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Modules | |
sequelize = require('sequelize') | |
# Connect to database | |
Sequelize = new sequelize('sequelize', 'sequelize', 'sequelize-test', | |
host: 'localhost' | |
port: '3306' | |
dialect: 'mysql' | |
syncOnAssociation: false | |
maxConcurrentQueries: 100 | |
) | |
# User model | |
modelUser = Sequelize.define('User', | |
id: | |
type: sequelize.INTEGER | |
allowNull: false | |
primaryKey: true | |
unique: true | |
autoIncrement: true | |
username: | |
type: sequelize.STRING(20) | |
allowNull: false | |
validate: | |
isAlphanumeric: | |
args: true | |
msg: 'Username can only contain alphanumeric values' | |
len: | |
args: [3, 20] | |
msg: 'Username must be between 3 and 20 characters in length' | |
) | |
# Force cre tables | |
Sequelize.sync({force: true}).success(-> | |
# Create a new model instance and save it into the database | |
model = modelUser.create( | |
username: 'admin' | |
).success(-> | |
# Try to find the user in the database | |
modelUser.find( | |
where: username: 'admin' | |
).success((user) -> | |
if !user then throw new Error('Could not find user') | |
# User was found, modify its username and try to save | |
user.username = 'wootroot' | |
user.save().success(-> | |
console.log('Everything went fine!') | |
).error((err) -> | |
# It will end here by saying that the username hasn't got the correct length | |
console.log('Something\'s wrong #2: ') | |
console.log(err) | |
) | |
) | |
) | |
).error((err) -> | |
console.log('Something\'s wrong #1: ' + err.toString()) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment