[英]How to get an array of references in Firestore?
I have the following structure in Firestore for my chats collection:我的聊天集合在 Firestore 中具有以下结构:
chats: [
chat1: {
jobs: [
jobs/job1,
jobs/job2,
jobs/job4
]
},
chat2: {
jobs: [
jobs/job2,
jobs/job3
]
}
]
If I'm on chat1
, and I have the data, then I have the array of references to jobs.如果我在
chat1
上,并且我有数据,那么我就有了对工作的引用数组。 I know I have jobs/job1
, jobs/job2
and jobs/job4
.我知道我有
jobs/job1
job1 、 jobs/job2
和jobs/job4
。
How can I query and get the data for all of these jobs?我如何查询和获取所有这些作业的数据?
I could do: firestore.doc("jobs/job1").get()
and firestore.doc("jobs/job2").get()
and firestore.doc("jobs/job3").get()
but that seems very inefficient.我可以这样做:
firestore.doc("jobs/job1").get()
和firestore.doc("jobs/job2").get()
和firestore.doc("jobs/job3").get()
但是似乎很低效。
And I don't understand how I can filter firestore.collection("jobs")
to give me what I want.而且我不明白如何过滤
firestore.collection("jobs")
来给我想要的东西。
I've seen a few other questions here asking the same thing, but for Java, and I'm unable to translate it into JavaScript.我在这里看到其他几个问题问同样的事情,但对于 Java,我无法将其翻译成 JavaScript。
I could do: firestore.doc("jobs/job1").get() and firestore.doc("jobs/job2").get() and firestore.doc("jobs/job3").get() but that seems very inefficient.
我可以这样做: firestore.doc("jobs/job1").get() 和 firestore.doc("jobs/job2").get() 和 firestore.doc("jobs/job3").get() 但那似乎非常低效。
That's exactly what you want to do - you can iterate the list and get each document individually.这正是您想要做的 - 您可以迭代列表并单独获取每个文档。 Firestore doesn't offer some optimized way to get multiple documents in one query using the web and mobile SDKs - it's plenty efficient just to get each one using its own query.
Firestore 没有提供一些优化的方法来使用网络和移动 SDK在一个查询中获取多个文档 - 仅使用自己的查询获取每个文档就非常有效。 You won't have any problems with this approach.
这种方法不会有任何问题。
See also: Google Firestore - how to get document by multiple ids in one round trip?另请参阅: Google Firestore - 如何在一次往返中通过多个 ID 获取文档?
import { deleteDoc, collection, doc, query, getDocs, setDoc } from "firebase/firestore"
const q = query(collection(db, 'collection_name'))
const querySnap = await getDocs(q)
querySnap.forEach((doc) => {
console.log("querySnap data", doc.data())
// reference is accessed as doc.ref
// if u wish u can push them to an array like myDocRefs.push(doc.ref)
console.log("querySnap data", doc.ref)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.