最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - "querySnapshot.forEach is not a function" in firestore - Stack Overflow

programmeradmin4浏览0评论

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                                         
  });                                      

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                                         
  });                                      

Share Improve this question edited Apr 3, 2018 at 5:39 Erfan Ahmed 1,6134 gold badges23 silver badges35 bronze badges asked Apr 3, 2018 at 3:35 Ivàn GonzalezIvàn Gonzalez 1091 gold badge1 silver badge3 bronze badges 4
  • 2 Did you try console.logging what querySnapshot was? – CertainPerformance Commented Apr 3, 2018 at 3:38
  • shouldn't the first argument be the error ? try function(error, querySnapshot) – Taki Commented Apr 3, 2018 at 3:39
  • 1 not in a Promise chain, @Taki ... .then callbacks only ever get a single argument when using Promises – Jaromanda X Commented Apr 3, 2018 at 3:42
  • Looks like you're doing everything correctly ~ firebase.google./docs/firestore/query-data/…. I'd remend stepping through with your browser's debugger – Phil Commented Apr 3, 2018 at 3:46
Add a ment  | 

5 Answers 5

Reset to default 2
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);
      });
  };
};

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')

It is not clear what you are doing with the rol and status variables. You have declared them as though you are storing a single value, yet you are returning an array of roles and iterating through them.

With regards to getting the results, if your browser supports ES6, then you could do the following:

let userRef1 = db.collection(`users/${currentUser.uid}/roles`)
let cont = 0
let rol;
let rolStatus;

return userRef1.get()
  .then(querySnapshot => {
    // Check if there is data
    if(!querySnapshot.empty) {
      // Create an array containing only the document data
      querySnapshot = querySnapshot.map(documentSnapshot => documentSnapshot.data());
      querySnapshot.forEach(doc => {
        let {rol, status} = doc;
        console.log(`rol: ${rol} - status: ${status}`);
      });
    } else {
      console.log('No data to show');
    }
  })
  .catch(err => {
    console.error(err);
  }); 

Please note: I've only tested this with the Node SDK

// Firebase App (the core Firebase SDK) is always required and must be listed first
import * as firebase from "firebase/app";
// Add the Firebase products that you want to use
import "firebase/auth";
import "firebase/firestore";
const firebaseConfig = {
  apiKey: "AIzaSyDNdWutrJ3Axpm-8ngNhzkzcw1g3QvkeFM",
  authDomain: "books-7bd8b.firebaseapp.",
  databaseURL: "https://books-7bd8b.firebaseio.",
  projectId: "books-7bd8b",
  storageBucket: "books-7bd8b.appspot.",
  messagingSenderId: "385706228283",
  appId: "1:385706228283:web:a3c2c9585dd74d54693a1e",
};
firebase.initializeApp(firebaseConfig);
export const firebaseAuth = firebase.auth();
export const firestore = firebase.firestore();
export default firebase;

You should check if it always exists before doing your logic:

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

         if(querySnapshot)
         {
           querySnapshot.forEach(function(doc) { 
           
           ...you thing

         }                                                                                                                         
})     
发布评论

评论列表(0)

  1. 暂无评论