We need to write to the database such a request:
parseCarList = [ { car_name: 'WV', parent_Id: null }, { car_name: 'Skoda', parent_Id: 'WV' }, { car_name: 'Opel', parent_Id: 'Skoda' }, { car_name: 'Ford', parent_Id: 'Skoda' }, { car_name: 'Peugeot', parent_Id: 'Skoda' }, { car_name: 'GM', parent_Id: 'WV' }, { car_name: 'Opel', parent_Id: 'GM' }, //Ошибка { car_name: 'Ford', parent_Id: 'GM' }, //Ошибка { car_name: 'Porche', parent_Id: 'GM' }, { car_name: 'Peugeot', parent_Id: 'GM' }, //Ошибка { car_name: 'Tesla', parent_Id: 'Peugeot' } ] We will not be given into the hierarchy of brands and their real involvement with each other.
The task of the cycle is to write to the database of the manufacturer and its parent, if there is one.
parseCarList.forEach(item => { if (item.car_name) { //если есть car_name db.cars.findAll({where: {name: item.car_name}}) .then(function (validCar) { if (validCar.length > 0) { // если нашли item.carid = validCar[0].dataValues.id; //тут еще будет записываться в базу родитель } if (validCar.length < 1) { // если не нашли createNewCar(item) .then(function (createdCar) { item.carid = createdCar.dataValues.id; //тут еще будет записываться в базу родитель }) .catch(error => console.log(error)); } }) .catch(error => console.log('Validation: ' + item.car_name + ' found Error: ' + error)); } }); Everything writes beautifully (all the machines are written to the database) except for those duplicate positions that I marked "Error", and I get an error because requests go asynchronously and by the time all iterations of the cycle go, the base does not have time to create a manufacturer and a duplicate request with the same manufacturer does not find it in the database trying to make this manufacturer again, but apparently by the time it starts to make such a record in the database will be, the car_name field is unique: true and I get an error:
New Car Opel not created, Error: SequelizeUniqueConstraintError: Validation error I will finish the beautiful view of the mistakes, do not pay attention.
Out to write in sync and wait for each machine created? And if on some kind of car the base gets stuck?
I add that I want to get in the end:
As a result, I want to get 2 tables in the database 1. Cars with fields id, car_name 2. Parents with fields id, car_id, parents_id
The Cars table will look like this:
id=1, car_name=WV id=2, car_name=Skoda id=3, car_name=Opel id=4, car_name=GM The Parents table will look like this:
id=1, car_id=2, parents_id=1 id=2, car_id=3, parents_id=2 id=3, car_id=3, parents_id=4
db.cars.findAll({where: {name: item.car_name}})? It is a bit confusing that both carName and parent are the same strings - Darth