Create new sequelize model
Here is an example of how to create a new Sequelize model:
// Import Sequelize and define the model
const { Sequelize, Model } = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql' // or 'postgres', 'sqlite', etc.
});
class User extends Model {}
User.init({
// Define the attributes of the model
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING,
unique: true
}
}, {
sequelize,
modelName: 'User'
});
In this example, we:
- Import Sequelize and define the
Model
class. - Create a new instance of Sequelize, passing in the database connection details.
- Define a new model class
User
that extends theModel
class. - Use the
init
method to define the attributes of the model. In this case, we define three attributes:id
,name
, andemail
. - Pass in the Sequelize instance and the model name (
'User'
) to theinit
method.
Once you've defined the model, you can use it to interact with your database. For example, you can create a new instance of the model and save it to the database:
const user = User.create({ name: 'John Doe', email: '[email protected]' });
You can also use the model to retrieve data from the database:
const users = await User.findAll();
Note that this is just a basic example, and you may need to customize your model to fit your specific use case. For example, you may need to add additional attributes, define relationships between models, or implement validation logic.