如何使用引用字段查询firestore集合
我有 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
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从你的问题来看,你似乎想要做一些像连接查询或像子查询这样的事情,这对于关系数据库来说是可能的。对于 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.