Skip to content

Database Seeds

When initially developing an application you often need dummy data for things like users, products, blog posts, etc.

Here are some of the challenges:

  • it's time consuming to create the data
  • getting realistic data
  • recreating the same data after you've updated during testing, development etc.

What if you had a way to automate creating dummy/test data at the push of a button? Enter database seeds!

StarterStack uses the Sequelize seeds functionality along with Faker to create dummy data and seed the database table.

Create a Seed File

TIP

These commands need to be run from inside the backend docker container

Accessing the Backend Docker Container

Run the following command to access the container.

sh
docker exec -it {container name}-api /bin/ash

The {container name} is the string you used for your project name when you installed StarterStack. If you want to see what containers are running you can run the following command:

sh
docker ps

Generate a Seed File

Next, run the following command to generate a new seed file:

sh
npx sequelize-cli seed:generate --name demo-products

This command will create a seed file in /backend/seeders folder. File name will look something like XXXXXXXXXXXXXX-demo-products.js. It follows the same up / down semantics as the migration files. You can basically apply and undo seeds.

Edit Your Seed File

In this step you need to create the actual records to seed your table with.

Here is an example using Faker to create products:

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

const generateProduct = () => {
    const product_name = faker.commerce.productName();
    const description = faker.person.productDescription();
    const date = new Date()
    return {
        product_name: product_name,
        description: description,
        createdAt: date,
        updatedAt: date,
    }
}

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up (queryInterface, Sequelize) {
    let totalProducts = 20;
    let products = [];

    for (let $i=0; $i < totalUsers; $i++) {
        totalProducts.push(generateProduct());
    }

    return queryInterface.bulkInsert('Products', users);
  },

  async down (queryInterface, Sequelize) {
    return queryInterface.bulkDelete('Products', null, {truncate:true});
  }
};

Run Your Seeds

From within your backend docker container, run the folling command:

sh
npx sequelize-cli db:seed:all

Your Products table is now seeded with dummy data.

You can read more about seeds in the Sequelize docs