angulartypescriptfirebasegoogle-cloud-firestorefavorites

Firebase set new data for each product separately


I have this firebase database and i'm trying to save in the database each product i click for favorite for the current user that acces in that moment. The problem is , i can only set 1 document, but i want to have separately each new doc in the favorite document.

I want to pass my 'uniqID' parameter that is the id of the product i click to favorite , to the database and automatically create new document with it's ID.. i tried with es6 structure , but didn't work.

enter image description here

firebase.service.ts

async addFavorites(
    uniqID: string,
    favorite_title: string,
    favorite_description: string,
    favorite_image: string,
    favorite_tag: string,
    favorite_stoc: boolean,
    favorite_reducere: number,
    favorite_price: number,
    favorite_userId: string
  ): Promise<void> {
    var user = firebase.auth().currentUser;

    if (user != null) {
      return await this.firestore
        .collection("users")
        .doc(user.uid)
        .set(
          {
            favoriteID: {
              // here i need to multiply this array by each product i click using parameter "uniqID"
              uniqueID: {
                favorite_title: favorite_title,
                favorite_description: favorite_description,
                favorite_image: favorite_image,
                favorite_tag: favorite_tag,
                favorite_stoc: favorite_stoc,
                favorite_reducere: favorite_reducere,
                favorite_price: favorite_price,
                favorite_userId: favorite_userId,
                isFavorite: true,
              },
            },
          },
          { merge: true }
        )
        .catch((err) => {
          console.log(err);
        });
    } else {
      console.log("Please Log In to add favorite!");
    }
  }

Solution

  • You need to use the square brackets notation as follows:

      const favoriteObj = {};
      favoriteObj[uniqId] = {
        favorite_title: favorite_title,
        favorite_description: favorite_description,
        favorite_image: favorite_image,
        favorite_tag: favorite_tag,
        favorite_stoc: favorite_stoc,
        favorite_reducere: favorite_reducere,
        favorite_price: favorite_price,
        favorite_userId: favorite_userId,
        isFavorite: true,
      };
    
      return await this.firestore
        .collection('users')
        .doc(user.uid)
        .set({ favoriteID: favoriteObj }, { merge: true })
        .catch((err) => {
          console.log(err);
        });