如何解决Node Sequelize Postgres-BulkCreate忽略自定义字段的重复值
目标:我有一个其他服务的对象列表,希望将其保留在自己的Postgres数据存储区中。来自该其他服务的数据返回JSON,但不包含任何ID。
当前成果:
- 当我第一次运行bulkCreate时,它将数据成功同步到我的数据库中(请参见下面的示例代码)
- 当我从其他服务获得新批次(即检查更新)并再次调用bulkCreate时,即使标题已经存在, new 主题也会插入到每一行的数据库中
预期结果
- 当我第一次运行bulkCreate时,它将数据成功同步到我的数据库中(请参见下面的示例代码)
- 当我从其他服务获得新批次(即检查更新)并再次调用bulkCreate时,仅插入标题未在数据库中找到的主题,其余主题的“ count”属性也将更新。
Topic.js
const database = require('../../shared/database'); // shared db connection. This works
const {DataTypes,Model} = require('sequelize');
class Topic extends Model { }
Topic.init({
topicId: {
type: DataTypes.INTEGER,primaryKey: true,autoIncrement: true,defaultValue: undefined,},title: {
type: DataTypes.STRING,allowNull: false,count: {
type: DataTypes.INTEGER,allowNull: true,{
sequelize: database,});
module.exports = Topic;
SyncAPI.js (第一次运行)-正常运行
const url = 'https://....'; // the remote service
const topics = await this.http.get(url); // simple example of getting the new data
// [{ 'title': 'Leadership','count': 214 },// { 'title': 'Management','count': 51 }]
await Topic.bulkCreate(topics);
// [{ 'topicId': 1,'title': 'Leadership',// { 'topicId': 2,'title': 'Management','count': 51 }]
SyncAPI.js (第二次运行)-创建重复项
const url = 'https://....'; // the remote service
const topics = await this.http.get(url); // note how the title is the same with updated counts
// [{ 'title': 'Leadership','count': 226 },'count': 54 }]
await Topic.bulkCreate(topics); // the old,inserted topics remaining,with new entries appended
// [{ 'topicId': 1,'count': 51 },// [{ 'topicId': 3,// { 'topicId': 4,'count': 54 }
我在这里看到续集文档(https://sequelize.org/master/class/lib/model.js~Model.html#static-method-bulkCreate),该文档说我可以指定'ignoreDuplicates'选项,但是它只能通过比较主键(“忽略主键的重复值”)来工作。
我正在bulkCreate()方法中寻找某种方式来使用自定义键“ title”指定“ ignoreDuplicates”,然后使用“ updateOnDuplicate”更新计数。
解决方法
我的最终解决方案是实际获取标题并将其转换为哈希,然后将其作为“ topic_uid”以UUID的形式存储在我的数据库中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。