如何在Firestore中的同一集合上查询Multile字段

时间:2020-07-31 11:03:26

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

我是Firebase和angular的新手,我想基于选定的过滤器在数据库中搜索事件,我进行了一些搜索并收集了一些代码以使其正常工作,

collection events{
  eventName: ...,
  eventTicketPrice,
  eventCategory
}

我已经设置了一些可观察的方法来监听过滤器按钮上的更改,这是我的代码

  items$: Observable<any[]>;
  categoryFilter$: BehaviorSubject<string | null>;
  priceFilter$: BehaviorSubject<string | null>;
  nameFilter$: BehaviorSubject<string | null>;
  dateFilter$: BehaviorSubject<string | null>;
  ageFilter$: BehaviorSubject<string | null>;

  startAt: BehaviorSubject<string | null>;
  endAt: BehaviorSubject<string | null>;
  // startobs = this.startAt.asObservable();
  // endobs = this.endAt.asObservable();

  constructor(
    public eventService: EventsService,
    private db: AngularFirestore
  ) {}

  mobileSize = [425, 375, 320];
  ngOnInit(): void {
    this.mobileSize.forEach((width) => {
      if (window.screen.width === width) {
        // 768px portrait
        this.mobile = true;
      }
    });

    this.categoryFilter$ = new BehaviorSubject(null);
    this.priceFilter$ = new BehaviorSubject(null);
    this.nameFilter$ = new BehaviorSubject(null);
    this.dateFilter$ = new BehaviorSubject(null);
    this.ageFilter$ = new BehaviorSubject(null);
    this.startAt = new BehaviorSubject(null);
    this.endAt = new BehaviorSubject(null);
    
    this.items$ = combineLatest(
      this.categoryFilter$,
      this.priceFilter$,
      this.nameFilter$,
      this.ageFilter$,
      this.startAt.pipe(debounceTime(500), distinctUntilChanged()),
      this.endAt.pipe(debounceTime(500), distinctUntilChanged())
    ).pipe(
      switchMap(([category, price, name, age, start, end]) => 
        this.db.collection('events', ref => {  
        let query : firebase.firestore.Query = ref;
        if (category !== null) { query = query.where('eventCategory', '==', category) };
        if (price == 'high' && price !== null) { query = query.orderBy('eventTicketPrice', 'desc') };
        if (price == 'low' && price !== null) { query = query.orderBy('eventTicketPrice', 'asc') };
        if (name == 'asc' && name !== null) { query = query.orderBy('eventName', 'asc') };
        if (name == 'desc' && name !== null) { query = query.orderBy('eventName', 'desc') };
        if (age !== null) { query = query.where('ageCategory', '==', age) };
        if (start && end !== null) { query = query.orderBy('eventName').startAt(start).endAt(end) };
        return query;
      }).valueChanges({ idField: 'id' }))
    );

目前,我可以按一个类别的单个过滤器进行过滤,但是在选择了价格过滤器和年龄过滤器等多个文件后,我无法过滤数据。

基本上我想通过选择过滤器来搜索数据

1 个答案:

答案 0 :(得分:0)

您当前的代码仅为eventCategoryageCategory添加过滤器。如果您还想为其他条件添加过滤器,则需要在查询中添加更多where子句。

例如,如果您想对eventTicketPrice进行过滤,而不是像现在的代码那样仅对其进行订购,则可以添加:

...
if (price == 'high') query = query.where('eventTicketPrice', '==', 'high');
...
return query;