【问题标题】:"querySnapshot.forEach is not a function" in firestoreFirestore 中的“querySnapshot.forEach 不是函数”
【发布时间】:2018-09-12 07:01:30
【问题描述】:

我正在尝试对数据库进行查询,以获取子集合“角色”的所有文档以重定向到不同的路由。

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

【问题讨论】:

  • 你试过console.logging querySnapshot 是什么?
  • 第一个参数不应该是错误吗?试试function(error, querySnapshot)
  • 不在 Promise 链中,@Taki ... .then 在使用 Promises 时,回调只会得到一个参数
  • 看起来你做的一切都是正确的~firebase.google.com/docs/firestore/query-data/…。我建议您使用浏览器的调试器逐步完成

标签: javascript firebase google-cloud-firestore


【解决方案1】:
// 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.com",
  databaseURL: "https://books-7bd8b.firebaseio.com",
  projectId: "books-7bd8b",
  storageBucket: "books-7bd8b.appspot.com",
  messagingSenderId: "385706228283",
  appId: "1:385706228283:web:a3c2c9585dd74d54693a1e",
};
firebase.initializeApp(firebaseConfig);
export const firebaseAuth = firebase.auth();
export const firestore = firebase.firestore();
export default firebase;

【讨论】:

    【解决方案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);
          });
      };
    };
    

    【讨论】:

    • 欢迎来到 Stack Overflow。请注意,您可以编辑您的答案;没有必要为同一个问题发布另一个答案。我建议您删除此答案或your other answer,然后根据需要编辑剩余的答案。此外,最好通过一些解释来增强您的纯代码答案。看看How do I write a good answer?。
    【解决方案3】:

    您应该在执行逻辑之前检查它是否始终存在:

    userRef1.get().then(function(querySnapshot) { 
    
             if(querySnapshot)
             {
               querySnapshot.forEach(function(doc) { 
               
               ...you thing
    
             }                                                                                                                         
    })     
    

    【讨论】:

      【解决方案4】:

      不清楚你在用rol 和status 变量做什么。您已将它们声明为存储单个值,但您正在返回一个角色数组并遍历它们。

      关于获取结果,如果您的浏览器支持 ES6,那么您可以执行以下操作:

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

      请注意:我只用 Node SDK 测试过这个

      【讨论】:

        【解决方案5】:

        我有一组用户,包括uid,就像你的一样。对于每个用户,它都包含一个名为friends 的子集合。

        目前,我正在为我的项目使用以下代码,没有任何问题。

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

        尝试修复您的代码

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

        到

        db.doc(`users/${currentUser.uid}`).collection('roles')
        

        【讨论】:

        • 您可以将其进一步缩短为let userRef1 = db.collection(<bt>users/${currentUser.uid}/roles<bt>)。我无法在评论中正确格式化。请将 替换为反引号
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-25
        • 2018-03-25
        • 1970-01-01
        • 2021-11-05
        • 2021-11-17
        • 2021-11-02
        • 2018-06-04
        相关资源
        最近更新 更多