'Adding data to nested collection firebase cloud firestore

Right now my firebase cloud firestore looks like this:

enter image description here

const db = fire.firestore();       

db.collection("groupFavs/"+groupID+ "/"+currentUserUID).add({favs: likedData})

The code above creates a collection called groupFavs, a document called groupID and another collection with the current users id. In the image I have above, it keeps creating documents for the users likes when i just want the currentuser id to only have one list in it which will be all their liked data. But instead it just keeps making multiple of them and I think its because of .add

I've tried using set but that wont work. Where am I going wrong?

 db.collection("groupFavs2")
    .doc(groupID).collection(currentUserUID)
     .set({
       favs: likedData
     })

I basically want to do something like this above but my logic is off in regards to the nested collection because what im calling above does not work



Solution 1:[1]

You can circumvent the string concatenation as well as the nested .collection .doc chain by using string interpolation as follows:

const collectionRef = db.collection(`groupFavs/${groupID}/${currentUserUID}`)

collectionRef.add({favs: likedData})

In regards to the multiple documents, you are adding a new document under the sub collection (matching the users id). Ideally this would look something like this:

  • Group Favs
    • 1st UserId
      • Like 1 doc
      • Like 2 doc
    • 2st UserId
      • Like 1 doc
      • Like 2 doc

Where the like doc can contain information related to the like such as image or liked boolean property.

If instead what you would like to do is keep a list of the users likes under their doc you can do it as follows:

const docRef= db.doc(`groupFavs/${groupID}/${currentUserUID}`)

const newLikeData = {
likes: firestore.FieldValue.arrayUnion(<your_like_information>)
}

docRef.set({favs: likedData}, {merge:true})

arrayUnion will append whatever data is in <your_like_information>.

Alternatively, you could query for the current likes list under the users doc, manually append the information and pass the entire object to a update or setDoc with merge: true.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rafael Zasas