您可以将public static bulkCreate(records: Array, options: Object): Promise<Array> 方法与options.ignoreDuplicates 一起使用。
忽略主键的重复值? (MSSQL 或 Postgres
此外,为模型上的message_uuid 字段添加unique 约束也很重要。这样查询将使用 Postgres 的ON CONFLICT DO NOTHING 子句。
例如,"sequelize": "^5.21.3" 和 postgres:9.6:
import { sequelize } from '../../db';
import { Model, DataTypes } from 'sequelize';
class Communication extends Model {}
Communication.init(
{
firstname: DataTypes.STRING,
lastname: DataTypes.STRING,
age: DataTypes.INTEGER,
message_uuid: {
type: DataTypes.INTEGER,
unique: true,
},
},
{ sequelize, tableName: 'communications' },
);
(async function test() {
try {
await sequelize.sync({ force: true });
// seed
await Communication.create({ firstname: 'teresa', lastname: 'teng', age: 32, message_uuid: 123 });
// test
await Communication.bulkCreate([{ firstname: 'teresa', lastname: 'teng', age: 32, message_uuid: 123 }], {
ignoreDuplicates: true,
});
} catch (error) {
console.log(error);
} finally {
await sequelize.close();
}
})();
执行结果:
Executing (default): DROP TABLE IF EXISTS "communications" CASCADE;
Executing (default): DROP TABLE IF EXISTS "communications" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "communications" ("id" SERIAL , "firstname" VARCHAR(255), "lastname" VARCHAR(255), "age" INTEGER, "message_uuid" INTEGER UNIQUE, PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'communications' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): INSERT INTO "communications" ("id","firstname","lastname","age","message_uuid") VALUES (DEFAULT,$1,$2,$3,$4) RETURNING *;
Executing (default): INSERT INTO "communications" ("id","firstname","lastname","age","message_uuid") VALUES (DEFAULT,'teresa','teng',32,123) ON CONFLICT DO NOTHING RETURNING *;
查看数据库,果然只有一行。
node-sequelize-examples=# select * from communications;
id | firstname | lastname | age | message_uuid
----+-----------+----------+-----+--------------
1 | teresa | teng | 32 | 123
(1 row)