Search code examples
firebaseangularfire2angularfire5

Angularfire Update nested data


I am using angularfire and firebase firestore database to save image data in a database. The saving works 100%.

My data is nested like this :

Images Collection

  • galleryId
    • imageId
      • name
      • path
    • imageId
      • name
      • path
  • galleryId
    • imageId
      • name
      • path

Sometimes I need to update a specific image object in the database, however, when I try do update an image object / doc I get the following error:

Invalid document reference. Document references must have an even number of segments, but images/yuEXbpYWqE4AUfmRCxIu/JvLzEANRFlupuUxYXNii has 3

This is the code I user :

this.afs.doc('images'+'/'+galleryId+'/'+imageId+'/').update({"name": upload.name,"path": upload.url});

I have also tried :

this.afs.doc('images').collection(galleryId).doc(imageId).update({"name": upload.name,"path": upload.url});

and I have also tried :

 this.afs.collection('images'+'/'+galleryId).doc(imageId).update({"name": upload.name,"path": upload.url});

and then I get a similar error, just referencing the collection this time :

 Invalid collection reference. Collection references must have an odd number of segments, but images/AHcWODRgsespIExQnJae has 2

When I try to update other collections in my database it works fine, however, they are only nested 2 levels. It seems that when you have nested 3 levels there are issue.

Please help


Solution

  • You cannot have a document nested directly under another document. You have to structure your nests accordingly: collection - document - collection - document - etc. Firestore paths always start with a collection.

    this.afs.doc('images/'+galleryId + '/images/' + imageId).update({"name": upload.name,"path": upload.url});
    

    I would suggest reading the firestore documentation as this is a fundamental aspect of firestore: https://firebase.google.com/docs/firestore/