1

I'm creating a recipes app just to learn Vue and Firebase Realtime Database.

This is the recipe structure:

{
  "name": "Stackoverflow shake",
  "description": "",
  "ingredients": {
    "-MLikewQrETdTWM12NVY": {
      "color": "red",
      "name": "Strawberries"
    },
    "-MLilh_HCnqX7Op7QmZ9": {
      "color": "purple",
      "name": "Pear"
    }
  }
}

And this is the ingredient structure:

{
  "name": "Pear",
  "color": "purple"
}

I have no problem creating or updating the recipe, but when I update an ingredient, to just change it's color, I'm having troubles to update all the recipes that contain that ingredient in particular.

Say I update the ingredient Pear to color: "green". The recipe Stackoverflow shake is still showing the Pear purple.

I guess that I have to iterate all the recipes that contains Pear, and update the color but I can't filter them.

What I tried:

updateIngredient({state}, payload) {
      // THIS WORKS
      db.ref("ingredients/" + payload.content.id)
      .update(payload.content).then((test) => {
        console.log(test);
      });
      // THIS DOESN'T WORK (doesn't filter only the recipes that contain that ingredient
      let query = db.ref('recipes').orderByChild(
          'ingredients/' + payload.content.id);
      query.once('value', function (snapshot) {
        snapshot.forEach(function (recipeSnapshot) {
          console.log(recipeSnapshot);
          db.ref('recipes/' + recipeSnapshot.key + '/ingredients/'
              + payload.content.id).update(payload.content);
        })
      });
    },

The second part of that method just adds the Pear ingredient to all the recipes, it doesn't filter the recipes to only the ones that have Pear.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Savandy
  • 363
  • 1
  • 3
  • 14
  • 1
    Your current data structure makes it easy to find all ingredients for a given recipe. It does not however make it easy to find all recipes for a given ingredient. To allow that use-case you'll need to add an additional data structure that maps each ingredient (ID) back to the recipes. For more on this see https://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value and https://stackoverflow.com/questions/41527058/many-to-many-relationship-in-firebase – Frank van Puffelen Dec 09 '20 at 19:19

1 Answers1

1

Check this discussion, it is pretty interesting. It`s about mongodb, but since they're both noSQL, the ideas are still valid. Good read.

Unfortunately, realtime database is not particularly good with querying and filtering, afaik, that is not even possible. Firestore would be better for that.

The only option you have here is querying all recipes, filtering those with "pear" and update the color. Then update the document again in the database

Thales Kenne
  • 2,705
  • 1
  • 12
  • 26