简体   繁体   English

如何使用模块 Web SDK 的版本 9 获取 Cloud Firestore 集合中的所有文档?

[英]How do I get all documents in a Cloud Firestore collection using Version 9 of the Modular Web SDK?

I am trying to get all documents in a collection using version 9 of the Web SDK. But I am getting this error:我正在尝试使用 Web SDK 的版本 9 获取集合中的所有文档。但我收到此错误:

"TypeError: querySnapshot.map is not a function" “类型错误:querySnapshot.map 不是函数”

This is the component where I get the error:这是我收到错误的组件:

import { useEffect, useState } from "react";
import { collection, getDocs } from "firebase/firestore";
import { db } from "../../firebase";
function CurrentUser() {
  const [names, setNames] = useState([]);
  async function getMakers() {
    const querySnapshot = await getDocs(collection(db, "users"));
    querySnapshot.map((doc) => {
      setNames((doc.id = doc.data()));
    });
  }
  getMakers();
  return <div>{names.map((doc) => doc.firstName)}</div>;
}
export default CurrentUser;

querySnapshot is an instance of a QuerySnapshot object, not a JavaScript Array. querySnapshotQuerySnapshot object 的实例,而不是 JavaScript 数组。 This means it doesn't have the normal Array methods like map() , some() and includes() .这意味着它没有普通的 Array 方法,如map()some()includes() However, it does have its own version of a forEach() method that can be used to iterate over the entries in the snapshot.但是,它确实有自己的forEach()方法版本,可用于迭代快照中的条目。 If you need to access methods of a normal array, you can use the snapshot's docs property instead (which internally calls forEach() to assemble an array).如果您需要访问普通数组的方法,则可以改用快照的docs属性(它在内部调用forEach()来组装一个数组)。

To correctly fetch the documents in the array, optionally plucking the first names of each returned document, you can use any of the following strategies:要正确获取数组中的文档,可选择提取每个返回文档的名字,您可以使用以下任何策略:

  • Option 1: useState and useEffect for each user's complete data方案一: useStateuseEffect对每个用户的完整数据
import { useEffect, useState } from "react";

// ...

const [userDataArray, setUserDataArray] = useState([]);

useEffect(() => {
  let unsubscribed = false;

  getDocs(collection(db, "users"))
    .then((querySnapshot) => {
      if (unsubscribed) return; // unsubscribed? do nothing.
      
      const newUserDataArray = querySnapshot.docs
        .map((doc) => ({ ...doc.data(), id: doc.id }));

      setUserDataArray(newUserDataArray);
    })
    .catch((err) => {
      if (unsubscribed) return; // unsubscribed? do nothing.

      // TODO: Handle errors
      console.error("Failed to retrieve data", err);
    });

  return () => unsubscribed  = true;
}, []);

return (
  <div>
    { userDataArray.map((userData) => userData.firstName) }
  </div>
);
  • Option 2: useState and useEffect for just each user's firstName选项 2:仅对每个用户的firstName使用useStateuseEffect
import { useEffect, useState } from "react";

// ...

const [firstNamesArray, setFirstNamesArray] = useState([]);

useEffect(() => {
  let unsubscribed = false;

  getDocs(collection(db, "users"))
    .then((querySnapshot) => {
      if (unsubscribed) return; // unsubscribed? do nothing.
      
      const newFirstNamesArray = querySnapshot.docs
        .map((doc) => doc.get("firstName"));

      setFirstNamesArray(newFirstNamesArray);

      // need to remove duplicates? use this instead:
      // const firstNamesSet = new Set();
      // querySnapshot
      //   .forEach((doc) => firstNamesSet.add(doc.get("firstName")));
      // 
      // setFirstNamesArray([...firstNamesSet]);
    })
    .catch((err) => {
      if (unsubscribed) return; // unsubscribed? do nothing.

      // TODO: Handle errors
      console.error("Failed to retrieve data", err);
    });

  return () => unsubscribed  = true;
}, []);

return (
  <div>
    { firstNamesArray }
  </div>
);
  • Option 3: Make use of a tree-shakeable utility library like react-use to handle intermediate states.选项 3:使用像react-use这样的 tree-shakeable 实用程序库来处理中间状态。
import { useAsync } from 'react-use';

// ...

const remoteUserData = useAsync(
  () => getDocs(collection(db, "users"))
);

if (remoteUserData.loading)
  return (<div>Loading...</div>);

if (remoteUserData.error) {
  console.error("Failed to load data! ", remoteUserData.error);
  return (<div class="error">Failed to load data!</div>);
}

const userDataArray = remoteUserData.value;

return (
  <div>
    { userDataArray.map((userData) => userData.firstName) }
  </div>
);

 useEffect(() => onSnapshot(collection(db, 'posts'), snapshot => { setPosts( snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })) ) }), [])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用模块 Web SDK 的版本 9 在 Cloud Firestore 集合中的文档中获取文档和嵌套集合? - How do I get document and nested collection in a document in a Cloud Firestore collection using Version 9 of the Modular Web SDK? 您如何使用 admin SDK 计算 firestore 集合中的文档? - How do you count documents in a firestore collection using the admin SDK? cloud firestore 快照是否读取集合中的所有文档? - Do cloud firestore snapshot reads all the documents in the collection? Firestore - Web 版本 9 - 获取集合中其 ID 在 ID 数组中的所有文档 - Firestore - Web version 9 - get all documents in collection whose id is in array of ids 如何获取 firestore 集合中的所有文档? - How to get all documents in a collection in firestore? 从 Firestore 集合中获取包含所有文档的列表 - Get a list with all documents from a Firestore collection 我如何知道是否还有更多文档需要从 Firestore 集合中获取? - How do I know if there are more documents left to get from a firestore collection? 如何从 Firestore 获取所有文档并进行循环(云功能) - how to get all documents from Firestore and make a loop (Cloud Functions) 如何从 Firestore 的集合中获取所有文档 - How to get all documents from a collection from Firestore 如何使用 Flutter 删除 Firestore 中集合中的所有文档 - How to Delete all documents in collection in Firestore with Flutter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM