Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does autoIncrement work in NodeJs's Sequelize?

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.

like image 202
Eric H. Avatar asked Apr 01 '13 05:04

Eric H.


People also ask

How do you autoIncrement in Sequelize?

To add the AUTO_INCREMENT attribute into the columns of your tables with Sequelize, you need to add the autoIncrement attribute into your Sequelize Model definition. For example, suppose you want to add an auto increment id column into the Users table.

What does autoIncrement do why is it used?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

How do you make a composite primary key in Sequelize?

You can create composite primary keys in Sequelize by specifying primaryKey: true against more than one column.


2 Answers

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.

like image 50
Yacine Rezgui Avatar answered Sep 20 '22 10:09

Yacine Rezgui


omitNull config option by default is false. Set it to true, and the id will be taken care of by Postgres:

sequelize = new Sequelize('mydb', 'postgres', null, {   host: 'localhost',   port: 5432,   dialect: 'postgres',   omitNull: true })  Visitor = sequelize.define('visitor', {   email: Sequelize.STRING })  Visitor.create({email: '[email protected]'}) 
like image 24
mxgrn Avatar answered Sep 19 '22 10:09

mxgrn