Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize defaultValue not getting set

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
        }
    });
};
like image 605
Andy Becker Avatar asked Mar 23 '16 20:03

Andy Becker


1 Answers

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 :)

like image 192
FastTurtle Avatar answered Oct 16 '22 06:10

FastTurtle