Skip to content

How to insert initial dummy data using Sequelize seeds/Faker

Last updated on November 17, 2022

This post is an extension of my previous post, Build a RESTful API Using Node, Express, and Sequelize. From the previous post, you can learn and set up your restful APIs. In this post, I would like to show creating or inserting dummy data using Sequelize seeds/Faker library.

Let’s install Faker:

npm install --save-dev @faker-js/faker

You will get similar output in the console

Now generate a seed file for the todos table using the Sequelize CLI seed generate command as shown below.

sequelize seed:generate --name todos

You will get similar output in the console

Now update generated seed file with the below code.

'use strict';
const { faker } = require('@faker-js/faker');

const todos = [...Array(100)].map((todo) => (
  {
    title: faker.lorem.words(),
    description: faker.lorem.text(),
    createdAt: new Date(),
    updatedAt: new Date()
  }
))

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up (queryInterface, Sequelize) {
      await queryInterface.bulkInsert('todos', todos, {});
  },

  async down (queryInterface, Sequelize) {
     await queryInterface.bulkDelete('todos', null, {});
  }
};

Run Seeders

Run seeds mean running SQL command to insert data provided in seeder files. You can run specific seed files or you can all seeds as shown below.

sequelize db:seed:all

You will get similar output in the console

Now you can check your database, you will find 100 fake records as configured in the code.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments