how i can fix the SequelizeDatabaseError: Field 'id' doesn't have a default value?

Viewed 13778

im working on a To do list in node using MVC node express pug and sequelize as ORM and the views part i made it with pug, so when i start my app works ok but when i try to create a new proyect and this proyect its gone to insert in the db the error 1364 appears

in principle it is a personal project to add to my portfolio, I saw that there is a possible solution by deactivating the STRICT SQL mode but I would like to know if there is another solution

model code Proyect.js

const Sequelize = require('sequelize');
//conect db
const db = require('../config/db');

const Proyects = db.define('proyects', {
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        allowNull: false
       },
    name: Sequelize.STRING,
    url: Sequelize.STRING
     });
module.exports = Proyects;

I expect with this model create a register in my table but when I try the actual error its the next

Executing (default): CREATE TABLE IF NOT EXISTS `proyects` (`id` INTEGER NOT NULL auto_increment , `name` VARCHAR(255), `url` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `proyects`
conected to db
Executing (default): INSERT INTO `proyects` (`id`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?);
{ SequelizeDatabaseError: Field 'id' doesn't have a default value
  code: 'ER_NO_DEFAULT_FOR_FIELD',
     errno: 1364,
     sqlState: 'HY000',
     sqlMessage: 'Field \'id\' doesn\'t have a default value',
     sql:
      'INSERT INTO `proyects` (`id`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?);' },
3 Answers

As per my understanding this is a problem with mysql database. The 'id' field in your table is marked as not null, and while inserting values you are not providing any value for the 'id' field.

You can avoid facing this error either allowing null values in the 'id' field or providing a default value (You can use defaultValue flag) while creating the table. Otherwise you already got an alternate solution.

I got this error initially as I had misspelled autoIncrement. To fix this, I used {force:true} as below after applying correct spelling and once the problem was gone, removed it from the sync() method. I will never use {force:true} in my production deployment as it drops the table (and deletes all your records).

in app.js, call sync method as follows

sequelize.sync({force:true})
    .then(result => {
        //console.log(result);
        app.listen(3000);
    })
    .catch(err => {
        console.log(err);
    });

you can install uuid npm install uuid then const uuid = require('uuid') use it anywhere you want for example id:uuid.v4()

Related