Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
30
rated 0 times [  35] [ 5]  / answers: 1 / hits: 6113  / 3 Years ago, wed, june 30, 2021, 12:00:00

So, i want to query some data from firestore.


this is my data structure


enter


so, the collection is Modules, then i now have 2 documents but it will be 75 or something. Then in that document i want to get the specific document which has a specific LessonId (In this example '2')
How do i query this?


this is wat i tries but it's not working for me


    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()

when i do this


    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()

it just works so it's something with my where statement i guess?


More From » firebase

 Answers
12

To use array-contains with an array of objects, you need to pass the complete object you are looking for in that array.


For example,


const lessonObj = {
Title: "Leven vanuit verlossing",
Description: "the desc",
...allTheOtherFieldsAsIs
}
firebase.firestore().collection("Modules").where("Lessons", "array-contains", lessonObj)

You should ideally use a sub-collection to store lessons in a module. Then you can easily query lessons using the following query:


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())

[#1158] Thursday, June 24, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anayaashleyh

Total Points: 597
Total Questions: 96
Total Answers: 86

Location: Papua New Guinea
Member since Thu, Jul 9, 2020
4 Years ago
anayaashleyh questions
;