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?
How would I create an index on the "author_id" and "title" column? 'use strict'; module. exports = { up: (queryInterface, Sequelize) => { return queryInterface. createTable('Todos', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.
A model is an abstraction that represents a table in your database. In Sequelize, it is a class that extends Model. The model tells Sequelize several things about the entity it represents, such as the name of the table in the database and which columns it has (and their data types). A model in Sequelize has a name.
You can create composite primary keys in Sequelize by specifying primaryKey: true against more than one column.
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;
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With