Estoy tratando de crear una serie de nuevos objetos usando los valores de un objeto existente para enviarlos a mi base de datos.
Aquí está el objeto existente:
{ name: 'Pasta', method: 'Cook pasta', ingredients: [ { measure: 'tbsp', quantity: '1', ingredient_name: 'lemon' }, { measure: 'g', quantity: '1', ingredient_name: 'salt' }, { measure: 'packet', quantity: '1', ingredient_name: 'spaghetti' }, { measure: 'litre', quantity: '1', ingredient_name: 'water' } ] } Básicamente, tengo una función que inserta y devuelve la identificación de la receta en una tabla, luego inserta y devuelve/o encuentra las identificaciones de los ingredientes relevantes y la parte final (con la que estoy luchando) es combinar la recipe_id devuelta, el ingredient_id y la measure y quantity correctas (como está escrito en el objeto de arriba).
Aquí es donde he llegado:
//starting point is here async function addNewRecipe(newRecipe, db = connection) { console.log(newRecipe) const recipeDetails = { recipe_name: newRecipe.name, recipe_method: newRecipe.method, } const ingredientsArray = newRecipe.ingredients const [{ id: recipeId }] = await db('recipes') .insert(recipeDetails) .returning('id') const ingredientsWithIds = await getIngredients(ingredientsArray) //returns an array of ids ingredientsWithIds.forEach((ingredientId) => { let ingredientRecipeObj = { recipe_id: recipeId, //works ingredient_id: ingredientId, //works measure: newRecipe.ingredients.measure, //not working - not sure how to match it with the relevant property in the newRecipe object above. quantity: newRecipe.ingredients.quantity,//not working - not sure how to match it with the relevant property in the newRecipe object above. } //this is where the db insertion will occur }) }La salida deseada sería:
ingredientRecipeObj = { recipe_id: 1 ingredient_id: 1 measure: tbsp quantity: 1 } then insert this into db followed by: ingredientRecipeObj = { recipe_id: 1 ingredient_id: 2 measure: g quantity: 1 } then insert into db etc. etc.El problema parece ser que la función "getIngredients" devuelve solo los ID. Una vez que los haya obtenido, no tiene forma de saber qué ID es para qué ingrediente. Una forma de cambiar eso es hacer que el método devuelva una matriz tanto del ID como del nombre del ingrediente. Entonces podrías emparejarlos así:
const ingredientsWithIds = await getIngredients(ingredientsArray) //now an array of objects with ingredient_name and id ingredientsWithIds.forEach((ingredient) => { const recipeIngredient = ingredientsArray.find(ri => ri.ingredient_name === ingredient.ingredient_name) const ingredientRecipeObj = { recipe_id: recipeId, ingredient_id: ingredient.id, measure: recipeIngredient.measure, quantity: recipeIngredient.quantity, } //this is where the db insertion will occur })Como no ha publicado la función "getIngredients", es difícil decir exactamente cómo adaptarla para que también devuelva el nombre.