目标: 我有一个来自另一个服务的对象列表,我想将这些对象保留在我自己的 Postgres 数据存储中。来自其他服务的数据返回 JSON,但不包含任何 ID。
当前结果:
预期结果
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', 'count': 214 },
// { '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 },
// { 'title': 'Management', 'count': 54 }]
await Topic.bulkCreate(topics); // the old, inserted topics remaining, with new entries appended
// [{ 'topicId': 1, 'title': 'Leadership', 'count': 214 },
// { 'topicId': 2, 'title': 'Management', 'count': 51 },
// [{ 'topicId': 3, 'title': 'Leadership', 'count': 226 },
// { 'topicId': 4, 'title': 'Management', 'count': 54 }
我在这里看到了 Sequelize 文档 (https://sequelize.org/master/class/lib/model.js~Model.html#static-method-bulkCreate),它说我可以指定一个 'ignoreDuplicates' 选项,但它只能通过比较主键(“忽略主键的重复值)来工作。我正在寻找bulkCreate() 方法中的某种方法,用我的自定义键'title' 指定'ignoreDuplicates',然后使用'updateOnDuplicate' 来更新计数。
最佳答案
我的最终解决方案是实际获取标题并将其转换为哈希,然后将其作为“topic_uid”作为 UUID 存储在我的数据库中。
关于node.js - Node Sequelize Postgres - BulkCreate 忽略自定义字段的重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63726887/