Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"querySnapshot.forEach is not a function" in firestore

I'm trying to do a query to the database, to get all documents of sub-collection "roles" to redirect to different routes.

let userRef1 = db.collection('users').doc(currentUser.uid).collection('roles')
let cont = 0
let rol = ''
let rolStatus = ''

userRef1.get().then(function(querySnapshot) {                                                                                                                               
  querySnapshot.forEach(function(doc) {                                                                                                                            

    cont++ 
    rol = doc.data().rol
    rolStatus = doc.data().status                                         
  });                                      

error on the console

like image 246
Ivàn Gonzalez Avatar asked Apr 03 '18 03:04

Ivàn Gonzalez


2 Answers

import { firestore } from "../../firebase";
export const loadCategories = () => {
  return (dispatch, getState) => {
    firestore
      .collection("CATEGORIES")
      .get()
      .then((querySnapshot) => {
        if (!querySnapshot.empty) {
          querySnapshot.forEach((doc) => {
            console.log(doc.id, "=>", doc.data());
          });
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };
};
like image 164
Ashwani Kumar Kushwaha Avatar answered Nov 12 '22 06:11

Ashwani Kumar Kushwaha


I have a collection of users including uid just like yours. And for each user, it contains a sub-collection called friends.

Currently, I'm using the following code for my project without having any issues.

module.exports = ({ functions, firestore }) => {
  return functions.firestore.document('/users/{uid}').onDelete((event) => {

    const userFriendsRef = getFriendsRef(firestore, uid);

     userFriendsRef.get().then(snapshot => {
       if (snapshot.docs.length === 0) {
         console.log(`User has no friend list.`);
         return;
      } else {
        snapshot.forEach(doc => {
          // call some func using doc.id
        });
      }
     }
  }
};

function getFriendsRef(firestore, uid) {
  return firestore.doc(`users/${uid}`).collection('friends');
}

Give it a try to fix your code from

db.collection('users').doc(currentUser.uid).collection('roles')

to

db.doc(`users/${currentUser.uid}`).collection('roles')
like image 1
JeffMinsungKim Avatar answered Nov 12 '22 05:11

JeffMinsungKim