Sequelize Model Instance
Introduction
In Sequelize, a popular Node.js ORM for relational databases like MySQL, PostgreSQL, SQLite, and others, Model Instances represent individual records (rows) within a table in your database.
In Sequelize, model instances represent individual records in a table. They encapsulate both the data for the record and methods to interact with that record within the database, providing a powerful way to work with data in a more object-oriented manner.Model Definition
A model in Sequelize corresponds to a table in the database. You define a model by extending Sequelize'sModelclass and specifying the attributes (columns) of the table.const { Sequelize, DataTypes, Model } = require('sequelize'); const sequelize = new Sequelize('database_name', 'username', 'password', { host: 'localhost', dialect: 'postgres', port: 5432, // The default port for PostgreSQL }); const User = sequelize.define( 'User', { // Model attributes are defined here firstName: { type: DataTypes.STRING, allowNull: false, }, lastName: { type: DataTypes.STRING, // allowNull defaults to true } }, { // Other model options sequelize, // pass the sequelize instance modelName: 'User' // Name of the model }, );Creating an Instance
A model instance is created by calling the
createmethod or by instantiating a new instance usingnew Model()and then saving it.// Using create method const user = await User.create({ firstName: 'John', lastName: 'Doe' }); console.log(user instanceof User); // true console.log(user.firstName); // "John"Instance Methods
Model instances come with built-in methods for interacting with the database, such as
save,destroy, andupdate.You can also define custom instance methods within the model definition.
// Built-in methods user.lastName = 'Smith'; await user.save(); // Updates the record in the database await user.destroy(); // Deletes the record from the databaseReloading an Instance
If you need to refresh an instance with the latest data from the database, you can use the
reloadmethod.await user.reload();Validations
Sequelize allows you to define validations on model attributes. These validations are automatically run before an instance is saved.
User.init({ firstName: { type: DataTypes.STRING, allowNull: false, validate: { notEmpty: true } }, });Instance Scopes
You can define scopes to automatically include certain conditions or attributes in your queries when working with model instances.
const users = await User.scope('active').findAll();