當表單已經加入了sequelize進行版本控管了之後,那麼在版本推進的時候常常也會有遇到一種狀況,例如:要預先塞入一些資料的狀況。也可以透過sequelize進行控管。
相關指令
sequelize-cli db:seed Run specified seeder
sequelize-cli db:seed:undo Deletes data from the database
sequelize-cli db:seed:all Run every seeder
sequelize-cli db:seed:undo:all Deletes data from the database
sequelize-cli seed:generate Generates a new seed file
sequelize-cli seed:create Generates a new seed file
npx sequelize-cli seed:generate --name init
Sequelize CLI [Node: 16.16.0, CLI: 6.4.1, ORM: 6.21.4]
Successfully created seeders folder at "/home/mars/testcode/database/dbMigrations/db/seeders".
New seed was created at /home/mars/testcode/database/dbMigrations/db/seeders/20221006135906-init.js .
可以看到產生了/home/mars/testcode/database/dbMigrations/db/seeders/20221006135906-init.js .這隻 seed file 。
'use strict';
module.exports = {
async up (queryInterface, Sequelize) {
/**
* Add seed commands here.
*
* Example:
* await queryInterface.bulkInsert('People', [{
* name: 'John Doe',
* isBetaMember: false
* }], {});
*/
},
async down (queryInterface, Sequelize) {
/**
* Add commands to revert seed here.
*
* Example:
* await queryInterface.bulkDelete('People', null, {});
*/
}
};
'use strict';
module.exports = {
async up (queryInterface, Sequelize) {
/**
* Add seed commands here.
*
* Example:
* await queryInterface.bulkInsert('People', [{
* name: 'John Doe',
* isBetaMember: false
* }], {});
*/
await queryInterface.sequelize.query(
"REPLACE INTO `users`(`id`, `parent`, `is_banned`, `account`, `password`, `created_time`, `updated_time`, `created_name`, `updated_name`) VALUES (1, 0, 0, 'admin', '$2b$10$3UxpBCmqN.cDdL/KRxYsP..VKyrD9l0N/lTbJWBDBwLU91heongte', '2022-10-03 08:01:38', '2022-10-03 16:01:38', NULL, 'admin');"
);
},
async down (queryInterface, Sequelize) {
/**
* Add commands to revert seed here.
*
* Example:
* await queryInterface.bulkDelete('People', null, {});
*/
await queryInterface.sequelize.query(
"DELETE FROM `users` WHERE id = 1;"
);
}
};
npx sequelize-cli db:seed:all
到此為止,資料庫的部分就已經準備好了,接下來就可以進行 api 的 CRUD,我們可以針對users這張表單進行資料的查詢、修改和刪除等等的操作,並且可以依此類推去規劃所有資料的寫入讀取了。