How to seed data with Knex — Basic
Populate tables with initial or test data using Knex seed scripts.
Learn: Seeds load repeatable test or demo data after migrations. Keep seeds idempotent where possible (delete then insert, or use upsert patterns) so `knex seed:run` is safe locally.
Supplementary examples
Seed function
exports.seed = async function (knex) {
await knex("users").del();
await knex("users").insert([
{ username: "demo" },
{ username: "tester" },
]);
};Course example
exports.seed = function (knex) {
// Deletes ALL existing entries
return knex("table_name")
.del()
.then(function () {
// Inserts seed entries
return knex("table_name").insert([
{ id: 1, colName: "rowValue1" },
{ id: 2, colName: "rowValue2" },
{ id: 3, colName: "rowValue3" },
]);
});
};
Additional references & examples
- Knex.js documentation
Query builder, migrations, seeds, and connection configuration.
- Knex seeds
Populate tables with initial or test data.