Uncaught (in promise) TypeError: snapshot.data is not a function when trying to retrieve documents from Firebase Firestore

Viewed 2275

I'm trying to retrieve all the documents inside a collection, but I get an error in return: Uncaught (in promise) TypeError: snapshot.data is not a function.

Code:

var imgRef = db.collection('posts').doc(uid).collection('userPosts');

        imgRef.get().then(function(snapshot) {

            const data = snapshot.data()

            console.log(data)

            if (data) {
                const picURL = data.picURL

                console.log(picURL)

                var img = document.querySelector(".img")

                img.src = picURL

            } else {

                console.log("PicURL doesn't exist")

            }
1 Answers

snapshot is going to be a QuerySnapshot (not a DocumentSnapshot) because the API doesn't know how many documents you're dealing with. QuerySnapshot doesn't have a data() method. You have to deal with each document data individually.

var imgRef = db.collection('posts').doc(uid).collection('userPosts');
imgRef.get().then(function(snapshot) {
    if (snapshot.docs.length > 0) {
        snapshot.docs.forEach(doc => {
            // doc is a DocumentSnapshot with actual data
            const data = doc.data();
        })
    }
    else {
        // decide what you want to do if there are no documents returned from the query
    }
});
Related