I am Quite new to Nest JavaScript/ type script. I am in the learning stage. But my client assigned a task to save user request in two tables. Here is the JSON request from user
{"title":"TITLE","groups":[{"group_id":1,"nutrients":[{"nutrient_id":1,"quantity":2,"unit":"mg"},{"nutrient_id":2,"quantity":2,"unit":"g"}]},{"group_id":2,"nutrients":[{"nutrient_id":2,"quantity":2,"unit":"mg"},{"nutrient_id":3,"quantity":2,"unit":"g"}]}]}
In profile table I need to save only title and timestamp. In nutrients table I need to save last inserted profile id, group id, nutrient id, quantity, and unit.
First of all i am not able to de structure the User input in proper way
. By the way, I have created related module, controller, entity, and service functionalities.But stuck up at Service functionality.
CodePudding user response:
Why not map over the array and build the desired data to be fed into the entity? For instance...
// Note:- Assuming the Json you shared is stored inside `const data`
const profile = await ProfileEntity.create({ title: data.title })
const nutrientsData = data.groups.flatMap(item => {
return item.nutrients.map(({ quantity, nutrient_id, unit }) => {
return {
group_id: item.group_id,
profile_id: profile.id,
nutrient_id,
unit,
quantity
}
})
})
await NutrientsEntity.create(nutrientsData);