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

时间:2019-02-23 14:50:47

标签: javascript firebase rxjs google-cloud-firestore angularfire2

假设我的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}}
]

然后我有两个查询:

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

然后我结合以进行化合物查询:

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

现在,我想向此查询中添加类似orderBy的内容,但是它到底如何工作?将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'));

然后合并结果将不会使最终的项目数组正确排序,因为每个列表都是单独排序的。

感觉应该记录在某处,但事实并非如此,我该怎么办?

1 个答案:

答案 0 :(得分:0)

您要在同一个集合上执行两个单独的查询,然后将它们合并到您的代码中(使用combineLatest)。这里有两件事要记住:

  1. 单独的查询可能包含重叠的结果。例如,带有{email: 'foo@bar.com', claims: {admin: true, support: true}}的文档将出现在两个查询中,因此同时出现在两个结果中。除非您的用例保证永远不会发生这种情况,否则您将需要决定如何处理这种重复的结果。
  2. 由于有两个单独的结果集,因此没有为合并结果定义任何顺序。只有您可以确定所需的最终订单,然后才需要确保合并代码确保该订单。我不是RxJS专家,但是希望您可以在pipe操作中执行此操作。
相关问题