Skip to content Skip to sidebar Skip to footer

How To Use Array-contains Operator With An Array Of Objects In Firestore?

So, i want to query some data from firestore. this is my data structure so, the collection is Modules, then i now have 2 documents but it will be 75 or something. Then in that doc

Solution 1:

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

Solution 2:

As Dharmaraj answered, the array-contains operator performs a complete match, so it only returns documents where the array contains the exact value you specified.

If you only want to filter on lesson IDs, I'd recommend adding an additional field to each document with just the lesson IDs. You can then filter on that field with:

firebase
        .firestore()
        .collection('Modules')
        .where('LessonsIDs', 'array-contains', 2)

Post a Comment for "How To Use Array-contains Operator With An Array Of Objects In Firestore?"