英文:
How to get an array of references in Firestore?
问题
我在Firestore的聊天集合中有以下结构:
chats: [
chat1: {
jobs: [
jobs/job1,
jobs/job2,
jobs/job4
]
},
chat2: {
jobs: [
jobs/job2,
jobs/job3
]
}
]
如果我在chat1
上,并且我有数据,那么我有对作业的引用数组。我知道我有jobs/job1
、jobs/job2
和jobs/job4
。
我如何查询并获取所有这些作业的数据?
我可以这样做:
firestore.doc("jobs/job1").get()
、firestore.doc("jobs/job2").get()
和firestore.doc("jobs/job3").get()
,但这似乎非常低效。
我不明白如何筛选firestore.collection("jobs")
以获取我想要的内容。
我看到有一些其他问题在这里提出了相同的问题,但是针对Java,我无法将其翻译成JavaScript。
英文:
I have the following structure in Firestore for my chats collection:
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. I know I have jobs/job1
, jobs/job2
and 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.
And I don't understand how I can filter firestore.collection("jobs")
to give me what I want.
I've seen a few other questions here asking the same thing, but for Java, and I'm unable to translate it into JavaScript.
答案1
得分: 2
> 我可以这样做:firestore.doc("jobs/job1").get() 和 firestore.doc("jobs/job2").get() 以及 firestore.doc("jobs/job3").get(),但这似乎非常低效。
这正是你想要做的 - 你可以迭代列表并单独获取每个文档。Firestore 并没有提供一种优化的方式来在一个查询中 使用 web 和移动 SDKs 获取多个文档 - 仅仅使用自己的查询来获取每个文档就足够高效了。你不会遇到任何问题。
另请参阅:https://stackoverflow.com/q/46721517
英文:
> 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.
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. You won't have any problems with this approach.
See also: https://stackoverflow.com/q/46721517
答案2
得分: 0
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)
})
英文:
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)
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论