如何通过 Firestore 中的引用字段连接来自两个集合的数据? [英] How to join data from two collections by reference field in Firestore?

查看:50
本文介绍了如何通过 Firestore 中的引用字段连接来自两个集合的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Firestore 中有 2 个系列.一个叫做所有者,第二个是独角兽.所有者只有一个名称字段,而独角兽具有名称和对所有者的引用.我想要一个查询来返回一个看起来像这样的对象数组

I have 2 collections in my firestore. One called owners and the second is unicorns. An owner has only a name field and a unicorn has a name and a reference to the owner. I want a query to return an array of objects that looks like this

unicorns = { id: 123,
                name: Dreamy,
                owner: { id: 1
                         name: John Cane
                       }
               }

我的查询看起来像这样,但缺少一些我无法弄清楚的东西

my query looks like this but there is something missing that I can't figure out

let unis = [];
      db
      .collection("unicorns")
      .get()
      .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          let uni = {
            id: doc.id,
            name: doc.data().name,
            owner: doc.data().owner,
          };
          if (uni.owner) {
            doc
              .data()
              .owner.get()
              .then((res) => {
                uni.owner = {
                  id: res.id,
                  name: res.data().name,
                };
                unis.push(uni);
                
              })
              .then(() => {
                setUnicorns(unis);
              })
              .catch((err) => console.error(err));
          } else {
            unis.push(uni);
          }
        });
      })

当我设置Unicorns hook并尝试映射结果时,我没有得到我需要的所有数据

When I setUnicorns hook and I try to map the results I don't get all the data I need

推荐答案

您不能对字符串运行 .get() 方法.您必须向 firestore 运行单独的请求才能获取所有者文档.我建议在异步函数中使用 for-of,如下所示.

You cannot run the .get() method on a string. You would have to run a separate request to firestore to get owner documents. I would recommend using a for-of inside a async function as shown below.

const db = admin.firestore()

//Declare the reference for collections before the loop starts
const ownersCollection = db.collection("owners")
const unicornsCollection = db.collection("unicorns")

const ownersData = {}

let unis = [];
unicornsCollection.get().then(async (querySnapshot) => {
    for (const doc of querySnapshot) {
        let uni = {
            id: doc.id,
            name: doc.data().name,
            //Assuming the owner field is the UID of owner
            owner: doc.data().owner,
        };
        if (uni.owner) {
            //Check if owner's data is already fetched to save extra requests to Firestore
            if (ownersData[uni.owner]) {
                uni.owner = {
                    id: ownersData[uni.owner].id,
                    name: ownersData[uni.owner].name,
                };
                unis.push(uni);
            } else {
                //User the ownersCollection Reference to get owner information
                ownersCollection.doc(uni.owner).get().then((ownerDoc) => {
                    uni.owner = {
                        id: ownerDoc.data().id,
                        name: ownerDoc.data().name,
                    };
                    ownersData[uni.owner] = {
                        id: ownerDoc.data().id,
                        name: ownerDoc.data().name,
                    }
                    unis.push(uni);
                }).then(() => {
                    setUnicorns(unis);
                }).catch((err) => console.error(err));
            }
        } else {
            unis.push(uni);
        }
    }
})

这是如何工作的?它获取所有 unicorn 文档,然后迭代以检查文档是否具有所有者的 UID.如果是,则向 Firestore 运行另一个请求以获取该独角兽的所有者文档.如果您有任何问题,请告诉我.

How this works? It fetches all the unicorn documents and iterates over then to check if the document has owner's UID. If yes then runs another request to Firestore to get that unicorn's owner's document. Let me know if you have any questions.

如果一个所有者拥有多个独角兽,那么您肯定不想一次又一次地获取同一所有者的数据.因此,将其添加到本地对象中,并在向 Firestore 发出请求之前检查是否已获取该所有者的数据.上面更新了相同的代码.

In case a single owner has multiple unicorns then you surely don't want to fetch the data of same owner again and again. So add that in an object locally and check if the data of that owner is already fetched before making a request to Firestore. Code for the same updated above.

这篇关于如何通过 Firestore 中的引用字段连接来自两个集合的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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