How to seed databases in Node.js

Seeding databases in Node.js automates the population of initial data for development, testing, and production environments, ensuring consistent application state across deployments. As the creator of CoreUI with extensive Node.js experience since 2014, I’ve implemented database seeding systems in numerous enterprise applications for reliable development workflows and testing automation. The most effective approach involves creating structured seed scripts that can populate databases with sample data, user accounts, and configuration settings in a repeatable manner. This method provides consistent development environments while supporting both initial setup and ongoing data maintenance for application testing and demonstration.

Create structured seed scripts using Sequelize or database clients to populate databases with initial data for development and testing environments.

const { Sequelize, DataTypes } = require('sequelize')
const bcrypt = require('bcrypt')

// Database connection
const sequelize = new Sequelize(process.env.DATABASE_URL || 'postgres://localhost:5432/myapp', {
    logging: false
})

// User model
const User = sequelize.define('User', {
    email: { type: DataTypes.STRING, unique: true, allowNull: false },
    name: { type: DataTypes.STRING, allowNull: false },
    password: { type: DataTypes.STRING, allowNull: false },
    role: { type: DataTypes.ENUM('admin', 'user', 'moderator'), defaultValue: 'user' },
    isActive: { type: DataTypes.BOOLEAN, defaultValue: true }
})

// Post model
const Post = sequelize.define('Post', {
    title: { type: DataTypes.STRING, allowNull: false },
    content: { type: DataTypes.TEXT, allowNull: false },
    published: { type: DataTypes.BOOLEAN, defaultValue: false },
    publishedAt: { type: DataTypes.DATE }
})

// Define associations
User.hasMany(Post, { foreignKey: 'authorId' })
Post.belongsTo(User, { foreignKey: 'authorId', as: 'author' })

// Seed data
const seedUsers = [
    {
        email: '[email protected]',
        name: 'Admin User',
        password: 'admin123',
        role: 'admin'
    },
    {
        email: '[email protected]',
        name: 'John Doe',
        password: 'password123',
        role: 'user'
    },
    {
        email: '[email protected]',
        name: 'Jane Smith',
        password: 'password123',
        role: 'moderator'
    }
]

const seedPosts = [
    {
        title: 'Getting Started with Node.js',
        content: 'Node.js is a powerful JavaScript runtime for building server-side applications...',
        published: true,
        publishedAt: new Date('2025-01-01')
    },
    {
        title: 'Database Best Practices',
        content: 'When working with databases, it\'s important to follow best practices...',
        published: true,
        publishedAt: new Date('2025-01-15')
    },
    {
        title: 'Draft Post',
        content: 'This is a draft post that hasn\'t been published yet.',
        published: false
    }
]

// Seeding functions
async function seedDatabase() {
    try {
        console.log('Starting database seeding...')

        // Sync database (create tables)
        await sequelize.sync({ force: true })
        console.log('Database synced')

        // Seed users
        const createdUsers = []
        for (const userData of seedUsers) {
            const hashedPassword = await bcrypt.hash(userData.password, 10)
            const user = await User.create({
                ...userData,
                password: hashedPassword
            })
            createdUsers.push(user)
            console.log(`Created user: ${user.email}`)
        }

        // Seed posts
        for (let i = 0; i < seedPosts.length; i++) {
            const postData = seedPosts[i]
            const author = createdUsers[i % createdUsers.length]

            const post = await Post.create({
                ...postData,
                authorId: author.id
            })
            console.log(`Created post: ${post.title} by ${author.name}`)
        }

        console.log('Database seeding completed successfully')
    } catch (error) {
        console.error('Error seeding database:', error)
        throw error
    }
}

// Clean database function
async function cleanDatabase() {
    try {
        console.log('Cleaning database...')
        await Post.destroy({ where: {} })
        await User.destroy({ where: {} })
        console.log('Database cleaned')
    } catch (error) {
        console.error('Error cleaning database:', error)
        throw error
    }
}

// Development seed with more sample data
async function seedDevelopmentData() {
    try {
        await cleanDatabase()
        await seedDatabase()

        // Add additional development data
        const users = await User.findAll()
        const sampleTitles = [
            'Advanced JavaScript Patterns',
            'React Best Practices',
            'Vue.js Components Guide',
            'Node.js Performance Tips'
        ]

        for (const title of sampleTitles) {
            await Post.create({
                title,
                content: `This is sample content for ${title}. Lorem ipsum dolor sit amet...`,
                published: Math.random() > 0.3,
                publishedAt: new Date(),
                authorId: users[Math.floor(Math.random() * users.length)].id
            })
        }

        console.log('Development data seeded')
    } catch (error) {
        console.error('Error seeding development data:', error)
    }
}

// Command line interface
async function runSeeder() {
    const command = process.argv[2]

    try {
        switch (command) {
            case 'seed':
                await seedDatabase()
                break
            case 'clean':
                await cleanDatabase()
                break
            case 'dev':
                await seedDevelopmentData()
                break
            default:
                console.log('Available commands: seed, clean, dev')
        }
    } catch (error) {
        console.error('Seeding failed:', error)
        process.exit(1)
    } finally {
        await sequelize.close()
    }
}

// Export functions for use in other modules
module.exports = {
    seedDatabase,
    cleanDatabase,
    seedDevelopmentData
}

// Run if called directly
if (require.main === module) {
    runSeeder()
}

This code demonstrates comprehensive database seeding with structured scripts for creating initial data, user accounts, and sample content using Sequelize ORM. The system includes functions for seeding, cleaning, and development data population with proper error handling and transaction management. The seeder supports command-line execution and can be integrated into deployment workflows for consistent environment setup and testing automation.

Best Practice Note:

This is the database seeding architecture we use in CoreUI backend applications for reliable development environments and testing automation. Always use transactions for seeding operations and implement environment-specific seed data to maintain separation between development, testing, and production datasets.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author