Last updated
What Is Database Seeding?
Database seeding populates a database with initial or test data. Seeds are used to set up development environments, run tests with known data, and populate lookup tables (countries, categories, roles) in production. Good seed data is realistic, covers edge cases, and is reproducible.
Generating Realistic Seed Data
JavaScript
import { faker } from '@faker-js/faker';
// Generate 100 realistic users
function generateUsers(count = 100) {
return Array.from({ length: count }, (_, i) => ({
id: i + 1,
name: faker.person.fullName(),
email: faker.internet.email().toLowerCase(),
phone: faker.phone.number(),
city: faker.location.city(),
country: faker.location.countryCode(),
createdAt: faker.date.past({ years: 2 }).toISOString(),
role: faker.helpers.arrayElement(['user', 'admin', 'moderator'])
}));
}
// Generate SQL INSERT statements
function toSqlInserts(tableName, rows) {
const cols = Object.keys(rows[0]).join(', ');
const values = rows.map(row =>
'(' + Object.values(row).map(v =>
v === null ? 'NULL' : `'${String(v).replace(/'/g, "''")}'`
).join(', ') + ')'
);
return `INSERT INTO ${tableName} (${cols}) VALUES
${values.join(',
')};`;
}
Seeding with Prisma
JavaScript
// prisma/seed.ts
import { PrismaClient } from '@prisma/client';
import { faker } from '@faker-js/faker';
const prisma = new PrismaClient();
async function main() {
await prisma.user.createMany({
data: Array.from({ length: 50 }, () => ({
name: faker.person.fullName(),
email: faker.internet.email()
})),
skipDuplicates: true
});
console.log('Seeded 50 users');
}
main().finally(() => prisma.$disconnect());