Here is my model for a recipe table. I am using mysql as the database, and the sequelize module. If I leave the title, prep_time, or cook_time blank in the form it seems to skip the validation of allowNull and defaultValue and attempts to enter a '' (blank string) into the database. Is there something I am doing wrong?
module.exports = function(sequelize, DataTypes) {
return sequelize.define('recipe', {
title: {
type: DataTypes.STRING,
allowNull: false
},
description: {
type: DataTypes.TEXT
},
ingredients: {
type: DataTypes.TEXT
},
instructions: {
type: DataTypes.TEXT
},
yield: {
type: DataTypes.STRING
},
prep_time: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: '0'
},
cook_time: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: '0'
},
image: {
type: DataTypes.STRING
}
});
};
This can happen in two cases. First, if you have entered the defaultValue
and allowNull
later after defining the model then you need to resync the table with sync({force: true)
.
Second, AllowNull
and defaultValue
will work if attributes like title
, and prep_time are not provided to create()
. for example create({title:'',prep_time:''})
will fill empty values. but if you do create({title:''}
then value of prep_time
be set the defaultValue
. Similary skipping title
attribute will cause validation error.
But if you are doing create(req.body)
and body has fields title
and prep_time
. then empty values will be entered.
Hope I made myself clear :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With