gpt4 book ai didi

javascript - 序列化 CreateOrUpdate 函数

转载 作者:行者123 更新时间:2023-12-03 22:37:07 26 4
gpt4 key购买 nike

我正在使用 node version v10.15.3"sequelize": "^4.22.8" 。使用 bulkCreate 时,我的数据库中出现双倍值:

我的模型如下所示:

module.exports = (sequelize, DataTypes) => {
const Company = sequelize.define('Company', {
name: DataTypes.STRING,
url: DataTypes.STRING,
symbol: DataTypes.STRING,
description: DataTypes.STRING,
}, {})
Company.associate = function(models) {
Company.hasMany(models.Rating)
};
return Company
};

我创建了一个自定义的 createOrUpdateCompany() 函数。在我的最小可执行示例下面找到:
const models = require('./src/models');
const Company = require('./src/models').Company;

async function getAllCompanies() {
try {
let res = await Company.findAll()
return res;
} catch (error) {
console.log(error)
}
}

async function createOrUpdateCompany(dataArray) {

if (dataArray === undefined || dataArray.length === 0) return ''

let iss = []

const allCompanies = await getAllCompanies()

// flatten array
dataArray = [].concat.apply([], dataArray)

if (allCompanies !== undefined) {
// 1. remove exact dedupes from dataArray
dataArray = [...new Map(dataArray.map(obj => [JSON.stringify(obj), obj])).values()]

// 2. compare dataArray to allCompanies and remove difference
// dataArray = dataArray.filter(cv => !allCompanies.find(e => e.symbol === cv.symbol))
dataArray = dataArray.filter(cv => !allCompanies.find(e => e.symbol === cv.symbol))

// 3. Remove null values for link and "" values for name
dataArray = dataArray.filter(cv => !(cv.name === '' || cv.url === null))
}

try {
iss = await Company.bulkCreate(dataArray, {
fields: [
'name',
'url',
'symbol',
'description',
]
})
} catch (error) {
console.log(error)
}
return iss
}

let data = [{
"date": "9/14/2019",
"issuer": "Issuer6",
"name": "Name1",
"symbol": "Symbol2",
"url": "www.url.com"
}, {
"date": "9/11/2029",
"issuer": "Issuer3",
"name": "Name1",
"symbol": "Symbol1",
"url": "www.url.com"
}, {
"date": "8/13/2019",
"issuer": "Issuer1",
"name": "Name1",
"symbol": "Symbol1",
"url": "www.url.com"
}]

async function main() {
// setup db
await models.sequelize.sync({
force: true
})

await createOrUpdateCompany(data)
await createOrUpdateCompany(data)
await createOrUpdateCompany(data)
await createOrUpdateCompany(data)

console.log("##################### DONE #####################");
}

main()

执行上面的示例时,我在我的数据库中得到以下信息:

enter image description here

但是,我只想得到以下结果:

enter image description here

如您所见,基于唯一结果,我只得到两个条目。

任何建议为什么我的 createOrUpdateCompany() 是错误的?

我感谢您的回复!

最佳答案

有两种方法可以让您的结果独一无二

  1. Filter your array data before execution (Javascript stuff) Unique elements from array

  2. Make specific fields unique in the DB (composite unique) (Database stuff)Add Composite unique key in MySQL

关于javascript - 序列化 CreateOrUpdate 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57978710/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com