Dung (Donny) Nguyen

Senior Software Engineer

How to Seed Data in Adonis.js

Database seeding in Adonis.js allows you to populate your database with initial or sample data, which is especially useful for development and testing.

Creating a Seeder

  1. Generate a seeder file using the Ace CLI:
    node ace make:seeder User
    

    This will create a file in database/seeders/, e.g., UserSeeder.ts.

  2. Edit the seeder file to define the data you want to insert. A typical seeder extends BaseSeeder and implements a run method:
    import BaseSeeder from '@ioc:Adonis/Lucid/Seeder'
    import User from 'App/Models/User'
    
    export default class UserSeeder extends BaseSeeder {
      public async run () {
        await User.create({
          email: 'example@adonisjs.com',
          password: 'secret',
        })
      }
    }
    

    You can also use methods like updateOrCreateMany to avoid duplicating records.

Running Seeders

Additional Notes

Summary:
To seed data in Adonis.js, create a seeder file, define your data in the run method, and execute node ace db:seed to populate your database.