I am new to NodeJS and Sequelize and am trying to execute the sequelize seeders on project startup.
Here is an example of one of my seed functions.
filePath: src/database/seeders/20220402125658-default-filters.js
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.bulkInsert('Filters', [
{
id: 'b16c15ce-9841-4ea5-95fb-0d21f8cd85f0', // TODO: use uuid4()
name: 'Amount Filter',
maxAmount: 200.0,
minAmount: 0.2,
createdAt: new Date(),
updatedAt: new Date(),
},
]);
},
async down(queryInterface, Sequelize) {
await queryInterface.bulkDelete('Filters', null, bulkDeleteOptions);
},
};
In my index.js file I am executing sequelize.sync() which synchronizes my database model. This is working great, but I want to also execute the seed code above when the sync is complete.
filePath: src/database/index.js
db.sequelize.sync().then(() => {
// execute seeders here ...
});
Do you have any idea how can I do that ?
The seeding is working correctly when I use it through npx command: npx sequelize-cli db:seed:all, but I want to do it automatically on project start.
A simple approach may be to write a script that runs the migrations/seeds via the Sequelize CLI and add in your package.json a start script that calls it, e.g. ./run-migrations.sh && node . (or maybe just sequelize-cli db:migrate && sequelize-cli db:seed:all && node .). Then just run npm run start to start the application.
Otherwise, from the looks of it, Sequelize has the umzug library for programmatically applying migrations/seeds. See the comment in this issue for how you might do this.
I'll copy the code here in case it's lost:
/* <PROJECT_ROOT>/migrations.js */ var Umzug = require("umzug"); var models = require("./models"); var migrationsConfig = { storage: "sequelize", storageOptions: { sequelize: models.sequelize // modelName: 'SequelizeMeta' // No need to specify, because this is default behaviour }, migrations: { params: [ models.sequelize.getQueryInterface(), models.sequelize.constructor ], path: "./migrations", // path to folder containing migrations pattern: /\.js$/ } }; var seedsConfig = { storage: "sequelize", storageOptions: { sequelize: models.sequelize, modelName: 'SequelizeData' // Or whatever you want to name the seeder storage table }, migrations: { params: [ models.sequelize.getQueryInterface(), models.sequelize.constructor ], path: "./seeds", // path to folder containing seeds pattern: /\.js$/ } }; var migrator = new Umzug(migrationsConfig); var seeder = new Umzug(seedsConfig); module.exports = () => migrator.up().then(() => seeder.up()); /* <PROJECT_ROOT>/index.js */ var migrations = require("./migrations"); // Run migrations & seeds migrations().then(function() { console.log("Migrations completed"); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With