我知道我目前已经注释掉了sequelize.sync。但否则它会自动生成我的表,我不知道我的 dbmigrate.js 是否真的有效。 我的问题:我想调用文件 dbmigrate.js。该文件应使用必要的表填充我的 MySQL 数据库。目前,它仅创建sequelizemeta表。但是当我运行命令
npx sequelize db:migrate
时,我得到了其他几个表。执行时没有收到任何错误消息,我不知道哪里出了问题。我尝试在网上寻找类似的例子,但无法找出我的错误。我已将我的代码放在下面。
初始化数据库并调用迁移文件和种子文件的文件。
// data/index.js
const config = require('config');
const {
getLogger,
} = require('../core/logging');
const {
sequelize,
} = require('./models');
const connectionTest = require('./tools/dbtest');
const migrate = require('./tools/dbmigrate');
//const seed = require('./tools/dbseed');
const isDevelopment = () => {
return config.get('env') === 'development' ? true : false;
};
async function initializeData() {
// Syncs the database and uses alter to push the model changes if the table already exists
/*
await sequelize.sync({
alter: true,
});
*/
// Test the Connection
await connectionTest();
// Migrate
await migrate();
// Seed
//if (isDevelopment()) await seed();
}
async function shutdownData() {
const logger = getLogger();
logger.info('Shutting down database connection');
await sequelize.close();
logger.info('Database connection closed');
}
module.exports = {
initializeData,
shutdownData,
};
创建sequelize实例
// data/models/index.js
'use strict';
// Generated using npx sequelize init
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
// Added by me
const config = require('config');
// Deconstructing database variables
const [DATABASE_NAME, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_HOST, DATABASE_DIALECT, DATABASE_PORT] = [config.get('database.name'), config.get('database.username'), config.get('database.password'), config.get('database.host'), config.get('database.dialect'), config.get('database.port')];
const db = {};
// Initializing the Sequelize database
// npx sequelize init puts there database in the models folder,
// for that reason I keep it here (data/models/index.js) instead of moving it to the index.js in the data folder
const sequelize = new Sequelize(
DATABASE_NAME,
DATABASE_USERNAME,
DATABASE_PASSWORD, {
host: DATABASE_HOST,
dialect: DATABASE_DIALECT,
port: DATABASE_PORT,
logging: true,
},
);
fs
.readdirSync(__dirname)
.filter((file) => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach((file) => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
module.exports = db;
//我的迁移代码(哪里出了问题)
// data/tools/dbmigrate.js
const {
Umzug,
SequelizeStorage,
} = require('umzug');
const {
getLogger,
} = require('../../core/logging');
const {
sequelize,
} = require('../models/');
module.exports = async function migrate() {
const logger = getLogger();
const migrator = new Umzug({
migrations: {
glob: '{../migrations/*.js}',
},
context: sequelize.getQueryInterface(),
storage: new SequelizeStorage({
sequelize: sequelize,
}),
logger: console,
});
let migrationSuccessful = true;
try {
await migrator.up();
logger.info('Succesful migration');
} catch (error) {
migrationSuccessful = false;
logger.error('Error while migrating the database', {
error,
});
}
if (!migrationSuccessful) {
try {
await migrator.down();
logger.info('Succesful migration after reverting the latest migration');
} catch (error) {
logger.error('Error while migrating the database', {
error,
});
}
throw new Error('Migrations failed');
}
};
迁移文件示例(使用sequelize-cli生成):
// data/migrations/20221121195900-create-user.js
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, DataTypes) {
await queryInterface.createTable('users', {
userID: {
primaryKey: true,
type: DataTypes.UUID,
allowNull: false,
},
firstName: {
type: DataTypes.STRING,
allowNull: false,
},
lastName: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
dateOfBirth: {
type: DataTypes.DATE,
allowNull: false,
},
gender: {
type: DataTypes.ENUM('M', 'F'),
allowNull: false,
},
createdAt: {
allowNull: false,
type: DataTypes.DATE,
},
updatedAt: {
allowNull: false,
type: DataTypes.DATE,
},
});
},
async down(queryInterface) {
await queryInterface.dropTable('users');
},
};
我必须使用迁移的绝对路径,而不是相对路径来访问迁移。
以前(不起作用):
migrations: {
glob: '{../migrations/*.js}',
},
路径现在看起来像这样(有效):
migrations: {
glob: '{src/data/migrations/*.js}',
}