Using MySQL, Node.js, Knex, Promise.
First time work with Promise, Knex and Node. I am not able to achive given task because of Promise and async calls I am not used to them.
The idea is the following - having two tables (products
and parts
). Data were migrated there using some bulk inserts. There is in-between table "products_parts
", it is not filled and I need to create node js code to fill in this table. When data would be filled in, then in the futre we would still need sometimes to call this function for some seperate products.
Here is algorithm:
- Query products
- For each product that is queried - take
product.description
and divide it into parts (split by commas). For instance, ifdescription = "A1, B1, C1"
then we would have three parts -A1
,B1
andC1
and need process each of them. Do next step with with products part (call it
PART
) - this is written in FOR loop now, but probably should be somehow replaced by Promise something.Try to find
PART
in database "parts
" table.- If found then do insert into db "
product_parts
". - If not found then first populate "PARTS" table with newly found PART. And then also populate "product_parts" table.
- If found then do insert into db "
I started like this:
knex("products")
.select("id", "description")
.map(function (row) {
// do staff with products.descriptin, simplified version:
var descriptionSplitByCommas = desc.split(",");
// do staff with each description PART here
// This for is not async and I believe is a bad idea, but how?!
for (var k = 0; k < descriptionSplitByCommas.length; k++) {
// STEP 3-4 should be here
// normalisation includes some string functions to be called
d = get_normalised_description(descriptionSplitByCommas[k]);
knex("PARTS")
.where("name", "=", d)
.first()
.then(function (row) {
if (row != undefined) { //not found
// do knex insert into "product_parts" table
} else {
// do knex insert into "PARTS" table
// do knex insert into "PRODUCT_PARTS" table
}
})
}
})