如何使用引用字段查询firestore集合

发布于 2025-01-13 16:45:14 字数 1375 浏览 0 评论 0原文

我有 3 个 firestore 集合

在此处输入图像描述


在此处输入图像描述


在此处输入图像描述

我使用 Angular 13 和 @angular/fire ("firebase ”: “^9.4.0”)

现在要获取用户的所有项目,我有此代码有

import { Firestore, collectionData, collection, docData, doc, getDocs, query, where } from '@angular/fire/firestore';
...
constructor(private firestore: Firestore){}

async getProjects() {

        // get user
        const user = await firstValueFrom(docData(doc(this.firestore, '/users/ebq3CamTAWN8TFL5JCA6jdwIK2K3')))

        // get organizationRef
        const organizationRef = doc(this.firestore, user.organization.path)

        // get projects
        const projects = query(
            collection(this.firestore, 'projects'),
            where("organizationRef", "==", organizationRef)
        )

        const querySnapshot = await getDocs(projects)

        querySnapshot.forEach((doc) => {
            console.log(doc.id, " => ", doc.data());
        })
    }

没有一种方法可以一次性查询此代码?

I have 3 firestore collections

enter image description here


enter image description here


enter image description here

I use Angular 13 with @angular/fire ("firebase": "^9.4.0")

Now to get all projects of an user I have this code

import { Firestore, collectionData, collection, docData, doc, getDocs, query, where } from '@angular/fire/firestore';
...
constructor(private firestore: Firestore){}

async getProjects() {

        // get user
        const user = await firstValueFrom(docData(doc(this.firestore, '/users/ebq3CamTAWN8TFL5JCA6jdwIK2K3')))

        // get organizationRef
        const organizationRef = doc(this.firestore, user.organization.path)

        // get projects
        const projects = query(
            collection(this.firestore, 'projects'),
            where("organizationRef", "==", organizationRef)
        )

        const querySnapshot = await getDocs(projects)

        querySnapshot.forEach((doc) => {
            console.log(doc.id, " => ", doc.data());
        })
    }

Is there a way to query this in one shot?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

久光 2025-01-20 16:45:14

从你的问题来看,你似乎想要做一些像连接查询或像子查询这样的事情,这对于关系数据库来说是可能的。对于 Firestore 来说,不可能做这样的事情。因此,您正在执行的任务无法使用单个查询来完成。 Firestore 查询一次只能从单个集合中获取文档。如果您需要从多个集合中获取数据,则必须像在代码中那样编写多个查询才能获得所需的结果。

From your question it seems you want to do something like a join query or something like subquery which is possible with relational databases. With Firestore it is not possible to do something like that. So the task you are doing can not be done using a single query. A Firestore query can only get documents from a single collection at a time. If you need to get data from multiple collections you have to write multiple queries as you did in your code to get the desired result.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文