【发布时间】:2020-03-04 05:41:40
【问题描述】:
我正在尝试使用 sequelize 迁移向模型添加字段,并且需要从“向上”迁移中更新数据。但是,在迁移中调用数据库以更新数据不会完成或引发错误,它们只是挂起。
我正在尝试将registrationType 字段添加到我数据库中的现有模型中。这个字段不应该为空,所以我需要添加 'allowNull: false' 属性。尚未设置 registrationType 的旧注册应使用模型中已存在的数据更新为正确的类型。为此,我需要访问模型中的 ID 字段,获取链接对象(注册链接到具有locationtype 的位置)并使用它来确定registrationType。我在迁移中添加了代码,就好像它是更新某些数据的正常数据库操作一样,但是这些调用不会返回或抛出错误。
我不能(也不想)使用默认值,因为应该根据现有数据为每个注册确定该值(添加默认值将使 allowNull 属性过时)。 我的做法: - 添加没有“allowNull”约束的列(使用 addColumn) - 更新所有现有数据 - 添加“allowNull”约束(使用changeColumn)
"use strict";
/*const db = require("../models");
const Registration = db.Registration;
const Site = db.Site;
const Location = db.Location;
*/
const REGISTATION_MODEL = "Registrations";
module.exports = {
up: async (queryInterface, Sequelize) => {
const transaction = await queryInterface.sequelize.transaction();
try {
const Registration = await queryInterface.sequelize.import(
"../models/registration.js"
);
const Site = await queryInterface.sequelize.import(
"../models/site.js"
);
const Location = await queryInterface.sequelize.import(
"../models/location.js"
);
await queryInterface.addColumn(
REGISTATION_MODEL,
"registrationType",
{
type: Sequelize.STRING
},
{ transaction }
);
console.log(
" * Column added, going to update existing registrations."
);
const registrations = await Registration.findAll();
console.log(
`\tFound ${registrations.length} registrations to be updated.`
);
for await (const registration of registrations) {
const site = await Site.findByPk(registration.SiteId);
const location = await Location.findByPk(site.LocationId);
await registration.update(
{
registrationType: location.locationType
},
{ transaction }
);
}
console.log(`\tUpdated ${registrations.length} registrations.`);
console.log(" * Adding 'allowNull:false' to field.");
//allowNull: false
await queryInterface.changeColumn(
REGISTATION_MODEL,
"registrationType",
{ type: Sequelize.STRING, allowNull: false },
{ transaction: t }
);
await transaction.commit();
} catch (ex) {
await transaction.rollback();
console.error("Something went wrong: ", ex);
}
},
down: (queryInterface, Sequelize) => {
return queryInterface.removeColumn(
REGISTATION_MODEL,
"registrationType"
);
}
};
输出:
Loaded configuration file "config/config.json".
Using environment "development".
== 20191107134514-add-registration-types: migrating =======
* Column added, going to update existing registrations.
然后挂起。
此处显示的代码不会产生任何错误,也不会产生任何输出。我添加了 console.log 语句,并再次运行迁移,这表明代码在第一次 findAll() 调用时挂起。 谁能告诉我该怎么做?
【问题讨论】:
标签: javascript node.js sequelize.js database-migration sequelize-cli