San*_*cht 13 javascript firebase react-native google-cloud-firestore
所以,我想从 firestore 查询一些数据。
这是我的数据结构
所以,集合是模块,那么我现在有 2 个文档,但它将是 75 个左右。然后在该文档中我想获取具有特定 LessonId 的特定文档(在本例中为“2”)我如何查询?
这是我尝试过的,但它对我不起作用
async function getModuleData() {
let ModuleData = await firebase
.firestore()
.collection('Modules')
.where('Lessons', 'array-contains', {LessonId: 2})
.get()
.then(snapshot => {
snapshot.forEach(doc => {
console.log(doc.data())
})
});
} getModuleData()
Run Code Online (Sandbox Code Playgroud)
当我这样做时
async function getModuleData() {
let ModuleData = await firebase
.firestore()
.collection('Modules')
.where('Title', '==', 'Leven vanuit verlossing')
.get()
.then(snapshot => {
snapshot.forEach(doc => {
console.log(doc.data())
})
});
} getModuleData()
Run Code Online (Sandbox Code Playgroud)
它只是有效,所以我猜这与我的 where 语句有关?
Dha*_*raj 13
要与对象数组一起使用array-contains,您需要传递您在该数组中查找的完整对象。
例如,
const lessonObj = {
Title: "Leven vanuit verlossing",
Description: "the desc",
...allTheOtherFieldsAsIs
}
firebase.firestore().collection("Modules").where("Lessons", "array-contains", lessonObj)
Run Code Online (Sandbox Code Playgroud)
理想情况下,您应该使用子集合将课程存储在模块中。然后您可以使用以下查询轻松查询课程:
const db = firebase.firestore()
const lessonsSnapshot = await db.collection("Modules")
.doc("moduleID")
.collection("Lessons")
.where("Title", "==", "Leven vanuit verlossing")
.get()
console.log(lessonsSnapshot.docs[0].data())
Run Code Online (Sandbox Code Playgroud)
正如 Dharmaraj 回答的那样,该array-contains运算符执行完全匹配,因此它仅返回数组包含您指定的确切值的文档。
如果您只想过滤课程 ID,我建议您向每个文档添加一个仅包含课程 ID 的附加字段。然后您可以使用以下方法过滤该字段:
firebase
.firestore()
.collection('Modules')
.where('LessonsIDs', 'array-contains', 2)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9862 次 |
| 最近记录: |