使用sequelize模型upsert

时间:2017-10-11 13:16:37

标签: node.js postgresql sequelize.js

我尝试使用续集模式对数据进行upsert,但它将被创建为重复数据。

如果行不存在,我想要的是插入,如果存在则更新行。

这是我的续集模型:

module.exports = (sequelize, DataTypes) => {
    return sequelize.define('Contact', {
        id: {
            type: DataTypes.UUID,
            field: 'id',
            allowNull: false,
            autoIncrement: true,
            primaryKey: true
        },
        first_name: {
            type: DataTypes.STRING(100),
            field: 'first_name',
            allowNull: true
        },
        external_id: {
            type: DataTypes.STRING(255),
            field: 'external_id',
            allowNull: false,
            primaryKey: true
        }
    }, {
        schema: 'ec3owner',
        tableName: 'contact',
        timestamps: false
    });
};

和upsert的Sequelize方法:

function upsertRow(bodyParams) {
    console.log('bodyParams', bodyParams);
    Contact.upsert(bodyParams, {
            where: {
                external_id: bodyParams.external_id
            },
            individualHooks: true
        })
        .then(function(row) {
            console.log('row', row);
        })
}

使用的版本:

postgres:9.6

的package.json

"sequelize": "^3.30.4"
"pg": "^6.1.0",

1 个答案:

答案 0 :(得分:0)

请参阅续编文档:http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-upsert

您不得提供id值,这是其创建新记录而不是更新记录的原因。