i.brod
i.brod

Reputation: 4603

How to define an index, within a Sequelize model?

I'm trying to create a simple non-unique index for one of my SQL columns, inside a Sequelize model. I tried to follow this post :How to define unique index on multiple columns in sequelize .

This is my code:

module.exports = (sequelize, DataTypes) => {
    const Item = sequelize.define('Item', {
        itemId:  DataTypes.STRING,
        ownerId:  DataTypes.INTEGER,
        status: DataTypes.STRING,
        type: DataTypes.STRING,
        nature: DataTypes.STRING,
        content: DataTypes.STRING,
        moment: DataTypes.BIGINT,
        indexes:[
            {
                unique: 'false',
                fields:['ownerId']
            }
        ]

    });

    return Item;
};

I get this error:

Unhandled rejection SequelizeDatabaseError: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '[object Object], createdAt DATETIME NOT NULL, updatedAt DATETIME NOT NULL, P' at line 1

The code that i have in my server.js file is this:

models.sequelize.sync().then(function () {
    server.listen(port, () => {
        console.log('server ready')
    })
});

What is wrong with my setup? Is there any other way this can be done with Sequelize?

Upvotes: 18

Views: 29381

Answers (2)

Sudhanshu Sharma
Sudhanshu Sharma

Reputation: 192

It can work in single migration also.

In my case, just perform the addIndex after createTable method in the migration file

Migration:

return queryInterface.createTable('Item', {
    // columns...
}).then(() => queryInterface.addIndex('Item', ['OwnerId']))
.then(() => {
    // perform further operations if needed
});

it's work for me in the migration file.

Upvotes: 6

Roi
Roi

Reputation: 1003

Almost there. You should add indexes in a new object like this:

module.exports = (sequelize, DataTypes) => {
    const Item = sequelize.define('Item', {
        itemId:  DataTypes.STRING,
        ownerId:  DataTypes.INTEGER,
        status: DataTypes.STRING,
        type: DataTypes.STRING,
        nature: DataTypes.STRING,
        content: DataTypes.STRING,
        moment: DataTypes.BIGINT
    },
    {
      indexes:[
       {
         unique: false,
         fields:['ownerId']
       }
      ]
    });

    return Item;
};

Upvotes: 29

Related Questions