【问题标题】:Sequelize upsert or create without PKSequelize upsert 或创建无 PK
【发布时间】: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'
    }
}

我也尝试过findOrCreatefindCreateFind,它们都返回带有Cannot convert undefined or null to object 变体的错误。

我尝试将id: nullparams 一起包含在内,结果完全相同。

我成功的唯一方法是在参数中提供 PK,但这显然不可扩展。

如何在参数中不提供 PK id 的情况下更新模型实例?

【问题讨论】:

  • 我遇到了同样的错误。我怀疑库中存在错误
  • 您的id 列是否可能不是身份列?例如。假设您的 id 列是整数。 const schema = { id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true }}

标签: node.js sequelize.js upsert


【解决方案1】:
class Pet extends Model { }
//...you might have the id for the pet from other sources..call it petId
const aPet = Pet.findCreateFind({where: {id: petId}});
aPet.attribute1 = 'xyz';
aPet.attribute2 = 42;
aPet.save();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 2020-09-05
    • 2023-04-04
    • 2017-01-16
    相关资源
    最近更新 更多