Problem notNull Violation in Sequelize and Associations (hasMany and belongsTo)

577 views
Skip to first unread message

José Imaz

unread,
Aug 7, 2020, 9:33:31 PM8/7/20
to Sequelize
I have a problem with Sequelize. For simplicity, I have two models

```User``` and ```EmailAddress```

The definition of each one is:

**User**
```
sequelize.define('User', {
        idUser: {
            type: DataTypes.INTEGER,
            field: 'IdUser',
            allowNull: false,
            primaryKey: true,
            autoIncrement: true
        },
....

const EmailAddress = model.EmailAddress;

    User.hasMany(EmailAddress, {
        as: 'EmailAddresses',
        foreignKey: 'IdUser',
        onDelete: 'NO ACTION',
        onUpdate: 'NO ACTION'
    });
```

**EmailAddress**

```
sequelize.define('EmailAddress', {
        idEmailAddress: {
            type: DataTypes.INTEGER,
            field: 'IdEmailAddress',
            allowNull: false,
            primaryKey: true,
            autoIncrement: true
        },
        idUser: {
            type: DataTypes.INTEGER,
            field: 'IdUser',
            allowNull: false,
            references: {
                model: 'Users',
                key: 'IdUser'
            },
            onUpdate: 'NO ACTION',
            onDelete: 'NO ACTION'
        },
...
    const EmailAddress = model.EmailAddress;
    const User = model.User;

    EmailAddress.belongsTo(User, {
        as: 'User',
        foreignKey: 'IdUser',
        onDelete: 'NO ACTION',
        onUpdate: 'NO ACTION'
    });
```


Now, I when I want insert a register in both tables, with the next code

```
var oBaseIncludes = [{
    model: models.EmailAddress,
    as: 'EmailAddresses'
}]

var SavedUser = await models.User.create(oUser, {
    include: oBaseIncludes,
    transaction: t,
    logging: console.log
});

```

For simplicity oUser is a object with all the User info and 
```
            user.EmailAddresses = [{ 
                default : true,
                token : user.UserMemoToken
            }];
```

Sequelize throw an error **message:'notNull Violation: EmailAddress.idUser cannot be null'**

**But. If I add the line (before save the User)**

```
oUser.EmailAddresses[0].idUser = -1;
```

**This works!** (insert in both tables correctly, and not with idUser = -1)

It seems that Sequelize cannot set idUser in EmailAddresses. It seems that Sequelize cannot connect both models.

I hope anyone can help me!

Thanks in advance!
Reply all
Reply to author
Forward
0 new messages