从集合中获取所有记录,其中包含Firestore中的所有参考 [英] Get all records from collection with all refrences in Firestore

查看:44
本文介绍了从集合中获取所有记录,其中包含Firestore中的所有参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我目前无法访问,因为我无法从具有引用值的集合中获取所有记录.

Hi I'm currently blocked because I can't get all records from a collection with references values.

我想从集合 events 中获取所有记录(有效),但是当我想合并与 categoryId 相关联的 category 信息时,代码不再起作用.

I would like to get all records from collection events (it works) but when I wanna merge the category information associated with categoryId my code doesn't work anymore.

事件收集

类别集合

export const getEventsRequest = async () => {
  const output = [];
  const data = await firebase.firestore().collection('events').get();

  data.forEach(async (doc) => {
    const {
      name,
      address,
      city,
      duration,
      level,
      startDate,
      maxPeople,
      categoryId,
    } = doc.data();

    const { name: categoryName, color } = (
      await firebase.firestore().collection('categories').doc(categoryId).get()
    ).data();

    output.push({
      name,
      address,
      city,
      duration,
      level,
      startDate,
      maxPeople,
      category: { name: categoryName, color },
    });
  });

  return output;
};

React Native项目中的示例测试

  const [events, setEvents] = useState([]);
  const [isEventsLoading, setIsEventsLoading] = useState(false);

  const getEvents = async () => {
    setEvents([]);
    setIsEventsLoading(true);

    try {
      const evts = await getEventsRequest();
      setEvents(evts);
      setIsEventsLoading(false);
    } catch (e) {
      console.error(e);
    }
  };

  useEffect(() => {
    getEvents();
  }, []);

  console.log('events', events);

输出

events Array []

期望

events Array [
  {
    name : "blabla",
    address: "blabla",
    city: "blabla",
    duration: 60,
    level: "hard",
    startDate: "13/04/2021",
    maxPeople: 7,
    category: {
      name: "Football",
      color: "#fff"
    },
  },
  // ...
]

我不知道是否有一种更简单的方法来检索这种数据(例如mongo DB上有 populate 方法).

I don't know if there is a simpler method to retrieve this kind of data (for example there is populate method on mongo DB).

预先感谢您的回答.

推荐答案

使用 CollectionReference#get ,它返回一个 Promise ,其中包含一个 forEach 方法该类上的 Promise / async 不兼容,这就是为什么您的代码会按预期停止工作的原因.

When you use CollectionReference#get, it returns a Promise containing a QuerySnapshot object. The forEach method on this class is not Promise/async-compatible which is why your code stops working as you expect.

您可以做的是使用 QuerySnapshot#docs 获取集合中文档的数组,然后创建一个 Promise 返回函数来处理每个文档并然后将其与 Promise.all 一起使用,以返回已处理文档的数组.

What you can do, is use QuerySnapshot#docs to get an array of the documents in the collection, then create a Promise-returning function that processes each document and then use it with Promise.all to return the array of processed documents.

以最简单的形式,它看起来像这样:

In it's simplest form, it would look like this:

async function getDocuments() {
  const querySnapshot = await firebase.firestore()
    .collection("someCollection")
    .get();

  const promiseArray = querySnapshot.docs
    .map(async (doc) => {
      /* do some async work */
      return doc.data();
    });

  return Promise.all(promiseArray);
}

将其应用于您的代码会得到:

Applying it to your code gives:

export const getEventsRequest = async () => {
  const querySnapshot = await firebase.firestore()
    .collection('events')
    .get();

  const dataPromiseArray = querySnapshot.docs
    .map(async (doc) => {
      const {
        name,
        address,
        city,
        duration,
        level,
        startDate,
        maxPeople,
        categoryId,
      } = doc.data();

      const { name: categoryName, color } = (
        await firebase.firestore().collection('categories').doc(categoryId).get()
      ).data();

      return {
        name,
        address,
        city,
        duration,
        level,
        startDate,
        maxPeople,
        category: { name: categoryName, color },
      };
    });

  // wait for each promise to complete, returning the output data array
  return Promise.all(dataPromiseArray);
};

这篇关于从集合中获取所有记录,其中包含Firestore中的所有参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆