简体   繁体   English

Firebase-如何向复合查询添加orderBy?

[英]Firebase - How to add orderBy to compound query?

Say I have some dummy data in my users collection: 假设我的users集中有一些虚拟数据:

[
  {email: 'foo@bar.com', claims: {admin: true}}
  {email: 'foo1@bar.com', claims: {admin: true}}
  {email: 'foo2@bar.com', claims: {support: true}}
  {email: 'foo3@bar.com', claims: {support: true}}
  {email: 'foo4@bar.com', claims: {support: true}}
]

Then I have these two queries: 然后我有两个查询:

const admins = this.db.collection('users', (ref) => ref
 .where('claims.admin', '==', true));
const support = this.db.collection('users', (ref) => ref
 .where('claims.support', '==', true));

Which I then combine to make a compound query: 然后结合起来进行复合查询:

this.dataSub = combineLatest(
  admins.valueChanges(),
  support.valueChanges()
)
.pipe(
  map((items) => {
    return [].concat(...items);
  })
)
.subscribe((items) => {
  this.items = items;
});

Now I would like to add things like orderBy to this query, but how would that work exactly? 现在,我想在此查询中添加诸如orderBy东西,但是它将如何工作呢? Putting an orderBy on them like: orderBy在他们身上像:

const admins = this.db.collection('users', (ref) => ref
 .where('claims.admin', '==', true)
 .orderBy('email', 'asc'));
const support = this.db.collection('users', (ref) => ref
 .where('claims.support', '==', true)
 .orderBy('email', 'asc'));

And then combining the results won't make the final array of items sorted properly, since each list is sorted individually.. 然后合并结果将无法使最终的项目数组正确排序,因为每个列表都是单独排序的。

It feels like this should be documented somewhere but it's just not, how can I do this? 感觉应该将其记录在某处,但事实并非如此,我该怎么做?

You're performing two separate queries on the same collection, and then merging them in your code (with combineLatest ). 您将在同一个集合上执行两个单独的查询,然后将它们合并到您的代码中(使用combineLatest )。 There are two things to keep in mind here: 这里有两件事要记住:

  1. The separate queries may contain overlapping results. 单独的查询可能包含重叠的结果。 For example, a document with {email: 'foo@bar.com', claims: {admin: true, support: true}} would appear in both queries, and thus be in both results. 例如,一个带有{email: 'foo@bar.com', claims: {admin: true, support: true}}的文档将出现在两个查询中,因此出现在两个结果中。 Unless your use-case guarantees this will never happen, you'll need to decide what to do with such duplicate results. 除非用例保证永远不会发生,否则您将需要决定如何处理这种重复的结果。
  2. Since there are two separate result sets, there is no defined ordered for the combined results. 由于有两个单独的结果集,因此没有为合并结果定义任何顺序。 Only you can determine what you want the final order to be, and you'll need to then make sure your merging code ensures that order. 只有您可以确定所需的最终订单,然后才需要确保合并代码确保该订单。 I'm not an RxJS expert, but would expect that you'd do this in the pipe operation. 我不是RxJS专家,但是希望您可以在pipe操作中执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM