【发布时间】:2020-12-05 11:27:03
【问题描述】:
我无法在 Sequelize(v:6.9.0,PostGres 方言)中执行任何类型的 upsert 或创建。
使用开箱即用的 id 作为 PK,对 name 字段具有唯一约束。我已经禁用了时间戳,因为我不需要它们,而 upsert 正在抱怨它们。我已经尝试手动定义 PK id,并允许 Sequelize 神奇地创建它。这是当前的定义:
const schema = {
name: {
unique: true,
allowNull: false,
type: DataTypes.STRING,
}
};
class Pet extends Model { }
Pet.define = () => Pet.init(schema, { sequelize }, { timestamps: false });
Pet.buildCreate = (params) => new Promise((resolve, reject) => {
let options = {
defaults: params
, where: {
name: params.name
}
, returning: true
}
Pet.upsert(options)
.then((instance) => {
resolve(instance);
})
.catch(e => {
// message:'Cannot read property 'createdAt' of undefined'
console.log(`ERROR: ${e.message || e}`);
reject(e);
});
});
module.exports = Pet;
更新代码:
// handled in separate async method, including here for clarity
sequelize.sync();
// later in code, after db sync
Pet.buildCreate({ name: 'Fido' });
在调试中,options 显示正确:
{
defaults: {
name: 'Fido'
},
returning:true,
where: {
name: 'Fido'
}
}
我也尝试过findOrCreate 和findCreateFind,它们都返回带有Cannot convert undefined or null to object 变体的错误。
我尝试将id: null 与params 一起包含在内,结果完全相同。
我成功的唯一方法是在参数中提供 PK,但这显然不可扩展。
如何在参数中不提供 PK id 的情况下更新模型实例?
【问题讨论】:
-
我遇到了同样的错误。我怀疑库中存在错误
-
您的
id列是否可能不是身份列?例如。假设您的id列是整数。const schema = { id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true }}
标签: node.js sequelize.js upsert