Skip to main content

Command Palette

Search for a command to run...

Sequelize Setter Getter Virtuals

Published
View as Markdown
  1. Introduction
    In Sequelize, getters, setters, and virtuals are powerful tools that allow you to manipulate model attributes when retrieving or setting values. They provide an abstraction layer over the actual data stored in the database, giving you flexibility to control how data is handled in the application.
    Getters -Modify how data is retrieved.

    Setters - Modify how data is saved to the database.

    Virtuals - Fields that don’t exist in the database but can be derived through logic (commonly using getters).

    This functionality helps to manage how your application interacts with data, enforcing validation, normalization, and customization when needed.

  2. Getters
    A getter is a method that retrieves and manipulates an attribute’s value when accessing it. It is used to format or modify the value of an attribute before returning it.
    For example, if you store a user's first name and last name separately, you could define a getter for a full name,

     const User = sequelize.define('User', {
       firstName: {
         type: Sequelize.STRING,
       },
       lastName: {
         type: Sequelize.STRING,
       },
       // Getter for fullName
       fullName: {
         type: Sequelize.VIRTUAL,
         get() {
           return `${this.firstName} ${this.lastName}`;
         }
       }
     });
    

    In this example, whenever you access user.fullName, the getter concatenates firstName and lastName and returns the full name, even though fullName is not stored in the database.

  3. Setters

    A setter allows you to manipulate an attribute’s value before saving it to the database. It is used to preprocess data before storing it, such as normalizing input or applying transformations.

    For example, if you want to ensure that email addresses are always stored in lowercase,

     const User = sequelize.define('User', {
       email: {
         type: Sequelize.STRING,
         set(value) {
           this.setDataValue('email', value.toLowerCase());
         }
       }
     });
    

    In this case, when a user is saved, the setter converts the email field to lowercase before storing it in the database.

  4. Virtuals

    Virtuals are fields that don't exist in the database but can be created and used on the Sequelize model. They are often used in conjunction with getters to create derived values. It is used to create calculated or derived attributes that do not need to be stored in the database.

     const User = sequelize.define('User', {
       firstName: {
         type: Sequelize.STRING,
       },
       lastName: {
         type: Sequelize.STRING,
       },
       // Virtual attribute
       fullName: {
         type: Sequelize.VIRTUAL,
         get() {
           return `${this.firstName} ${this.lastName}`;
         }
       }
     });
    

    In this case, fullName is a virtual attribute that concatenates firstName and lastName but is never stored in the database.

  5. Combining Setters and Getters
    You can also combine setters and getters for the same attribute to ensure data is both preprocessed before being saved and formatted before being retrieved.

     const User = sequelize.define('User', {
       name: {
         type: Sequelize.STRING,
         set(value) {
           this.setDataValue('name', value.trim()); // Ensure no extra spaces
         },
         get() {
           return this.getDataValue('name').toUpperCase(); // Return in uppercase
         }
       }
     });
    

    Here, the setter ensures the name is trimmed before saving, and the getter ensures the name is returned in uppercase when retrieved.