如何将数组包含运算符与 Firestore 中的对象数组一起使用? [英] How to use array-contains operator with an array of objects in Firestore?

查看:15
本文介绍了如何将数组包含运算符与 Firestore 中的对象数组一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我想从 firestore 查询一些数据.

So, i want to query some data from firestore.

这是我的数据结构

所以,集合是模块,那么我现在有 2 个文档,但它将是 75 或什么的.然后在该文档中,我想获取具有特定 LessonId 的特定文档(在本例中为2")我如何查询?

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

当我这样做

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

它只是有效,所以我猜它与我的 where 语句有关吗?

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

推荐答案

要将 array-contains 与对象数组一起使用,您需要在该数组中传递您正在寻找的完整对象.

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

例如

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

这篇关于如何将数组包含运算符与 Firestore 中的对象数组一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆