Search code examples
angularfirebaseangularfire2

How to return an array from Firebase when a user's id matches the document uid


I would like to know how to retrieve an array or urls from Firebase with a query that checks that the current user's id matches the document uid, and if so, it returns the array of url strings outlined in image below.

enter image description here


Solution

  • With angularfire2 you can do as follows:

    this.itemDoc = afs.doc<any>('/lists/432jk....');  //You know the "the current user's id", then you can build the document ref (i.e. path)
    this.item = this.itemDoc.valueChanges();
    this.item.subscribe(value => {
      const urlsArray = value.urls;
    });
    

    More details in the documentation: https://github.com/angular/angularfire2/blob/master/docs/firestore/documents.md


    Or you could use the native JavaScript SDK as follows:

    var docRef = db.collection('lists').doc('/lists/432jk....');
    
    docRef.get().then(function(doc) {
        if (doc.exists) {
             const urlsArray = doc.data().urls;
        } else {
            // doc.data() will be undefined in this case
            console.log("No such document!");
        }
    }).catch(function(error) {
        console.log("Error getting document:", error);
    });