Sling Academy
Home/Node.js/How to Set Default Values in Sequelize.js (3 Ways)

How to Set Default Values in Sequelize.js (3 Ways)

Last updated: December 29, 2023

Learn some different ways to set default values in Sequelize.js and Node.js.

Solution 1: Model Definition Defaults

Define default values directly within the model’s attributes during its definition. This is the most straightforward method to set default values for a given column.

  • Step 1: Install Sequelize and set up your model.
  • Step 2: Define the model attributes, specifying the default value using the ‘defaultValue’ key.
  • Step 3: Sync or migrate your model to create the database schema.
const User = sequelize.define('User', {
  username: {
    type: Sequelize.STRING,
    defaultValue: 'Anonymous'
  }
});

Pros: Easy to implement; directly integrated into Sequelize’s model definitions.

Cons: Limited to static values or Sequelize-provided functions; not suitable for dynamic calculations based on other fields.

Solution 2: Virtual Fields with Hooks

Use virtual fields in combination with model hooks to compute default values dynamically based on other fields or logic.

  • Step 1: Define a virtual field in the model which will not be persisted in the database.
  • Step 2: Use the ‘beforeCreate’ hook to set the actual default value by applying logic to the virtual field’s value.
  • Step 3: Create instances of the model without specifying the value for the actual field to see the default being applied.
const User = sequelize.define('User', {
  username: Sequelize.STRING,
  defaultUsername: {
    type: Sequelize.VIRTUAL,
    defaultValue: 'Anonymous'
  }
});

User.addHook('beforeCreate', (user) => {
  if (!user.username) {
    user.username = user.defaultUsername;
  }
});

Pros: Allows for dynamic default values; can implement complex logic.

Cons: More complex to implement; virtual fields do not get persisted.

Solution 3: Database Level Defaults

Set default values directly on the database schema, using Sequelize to define the model with database-specific functions or expressions as default values.

  • Step 1: Define the model with database function or expression in defaultValue option.
  • Step 2: Sync or migrate your model to apply the defaults on the database level.
  • Step 3: Insert records into the database and observe the database applying default values.
const User = sequelize.define('User', {
  createdAt: {
    type: Sequelize.DATE,
    defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
  }
});

Pros: Offloads logic to the database; generally more performant.

Cons: Less flexibility in a Sequelize context; limited by database functions.

Final Words

In conclusion, setting default values in Sequelize can be achieved through model definitions, virtual fields with hooks, or database level defaults. The choice of solution depends on whether the defaults are static, dynamic, or if they would benefit from being database-centric. Developers should choose a method that suits their application’s needs while considering the trade-offs in terms of simplicity, flexibility, and performance.

Next Article: Working with Paranoid Tables in Sequelize

Previous Article: A Deep Dive into Sequelize’s Timestamps

Series: Sequelize.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates