如何使用 Firestore 执行动态 where 查询并添加索引 [英] How to perform dynamic where queries with firestore and add indexes

查看:28
本文介绍了如何使用 Firestore 执行动态 where 查询并添加索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网站中,我正在进行一项类似于 tests 的调查,每个测试都有 attendies 子集合,如下所示

In my site i am conducting a survey like tests, each test has attendies sub collection look like this

当有人完成测试时,我也会将他们的 uid 添加到 completed 字段,就像我在框中绘制一样.现在我想根据 status == completed 查询 tests.

When someone finishes a test i also add their uid to completed field like i drawn in the box. Now i want to query tests based on status == completed.

这是我试过的

    this.completedModulesRef$ = this.afs.collection('tests', ref => 
           ref.orderBy('moduleNum', 'desc')
              .where('completed.'+auth.uid+'.status','==','completed'));

    this.completedModules$ = this.completedModulesRef$.valueChanges();

然后firestore要求我添加索引,当我按照生成的链接添加索引时,我得到了这个

Then firestore asked me to add indexes, when i follow the generated link to add indexes i got this

它指向 completed.CurrentUserId.status.我相信这仅适用于当前用户.

which is pointing to completed.CurrentUserId.status. I believe this only work for current user.

我有几个问题

1) .where('completed.'+auth.uid+'.status','==','completed') 这是一个有效的查询吗?

1) .where('completed.'+auth.uid+'.status','==','completed') Is this a valid query?

2) 如果是,我该如何索引它?

2) If yes how can i index it?

3) 有什么方法可以根据子集合值查询顶级集合?.(这才是我真正想要的)

3) Any way to query the top collections based on sub collection value?. (this is what i really want)

感谢任何帮助.

推荐答案

您可以改为使用一组对象(每个对象代表一个参加者)来跟踪所有已完成的参加者.数组在 firestore 中建立索引.

You could just instead use an array of objects (each object represents one attendie) to track all the completed attendies. Arrays are indexed in firestore.

数组的数据结构为:

compeleted: [{}] = [
  {id: string, points: number, status: string}
]

这可能不是最佳的数据库模型,具体取决于您要获取数据的方式和位置,但它将被编入索引并且您将能够查询它.我会考虑将积分和状态存储在参加者的子集中.查看 firestore 中的分组集合查询 - 新功能,您可以在其中一次查询所有参加者子集合 - 如果您想获取一个参加者完成的所有测试,则可以查询具有特定 ID 和完成状态的任何参加者.

This might not be the most optimal database model depending on how and where you want to fetch the data but it will be indexed and you will be able to query it. I would consider storing the points and status in the subcollection of attendies. Have a look at grouped collection queries in firestore - new feature where you can query across all attendies subcollections at once - for any attendie with a certain id and a status of complete if you want to fetch all the tests that one attendie completed.

这篇关于如何使用 Firestore 执行动态 where 查询并添加索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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