0

I am creating a clothing e-commerce application integrated with woocommerce and Firestore.

I currently am trying to build the 'add to wishlist part, here I am struggling with trying to update the items 'favourite' field in the database.

I present my Firestore" my Firestore database

I have access to the item on my react native side I need to be able to iterate through the objects, compare the nested object items ID against the idea of the item I am currently clicking on and change the favorite field to true. Currently, I have tried to do the following, but to no avail.

const like = (item) => {
// db.collection("users").doc(user).collection("wishlist").doc(random).set({
//   id:item.id,
//   name:item.name,
// })

db.collection("users")
  .doc(user)
  .collection("products")
  .doc("0")
  .get()
  .then((data) => {
    const info = data.data();
  });

};

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Sheran Malik
  • 11
  • 1
  • 2

2 Answers2

0

In order to perform an update to an object that exists in an array-type field, you need to find that particular object first. Unfortunately, there is no way you can query a Firestore collection based on a value that exists in an object that is contained in an array. This kind of filtering cannot be achieved using partial data. To solve this, you have to read the array, find the desired elements that need to be updated, perform the update and then write the document back to Firestore.

I have also written an article called:

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
0

so at the end I came up with a solution which I thought I would share here:

const like = (item) => {
    const newData = { ...Data };
    if (newData !== null) {
      let index = newData.Products.findIndex((e) => {
        return e.id === item.id;
      });
      console.log(index);
      newData.Products[index].favourite = true;
      db.collection("users")
        .doc(userID)
        .collection("products")
        .doc("0")
        .set(newData)
        .then((data) => setData(data))
        .catch((error) => console.log(error));
    } else {
      alert("An error has occured");
    }
  };

so this takes the data, saves it, adds the particular change and sets it again

Sheran Malik
  • 11
  • 1
  • 2