How does autoIncrement work in NodeJs's Sequelize?

Eric H. picture Eric H. · Apr 1, 2013 · Viewed 47.8k times · Source

Sequelize's document doesn't say a whole lot about autoIncrement. It only includes the following example:

// autoIncrement can be used to create auto_incrementing integer columns
incrementMe: { type: Sequelize.INTEGER, autoIncrement: true }

Based off of this example I have the following code:

db.define('Entries', {
    id: {
        type: Seq.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    title: {
        type: Seq.STRING,
        allowNull: false
    },
    entry: {
        type: Seq.TEXT,
        allowNull: false
    }
}

Now when I want to create an entry I want to do something like this:

models.Entry.create({title:'first entry', entry:'yada yada yada'})

However, when I execute that code I get a database error:

Null value in column "id" violates not null constraint

I would assume Sequelize would put the integer in for me or define the database table to do that itself. Apparently not? What am I missing here to ensure that the id is automatically incremented and filled?

Thanks much.

Answer

Yacine Rezgui picture Yacine Rezgui · Apr 1, 2013

Normally Sequelize.js adapt itself with the database. So the autoincrement attribute corresponds to a serial type in PostgreSQL.

I already worked with Sequelize and what I remember is that you don't need to specify an id as a primary key. Sequelize will do it for you.

Try to not add an id attribute and see if Sequelize will not add it for you or not.