Firestore: How to get random documents in a collection

后端 未结 8 1711
旧巷少年郎
旧巷少年郎 2020-11-22 10:08

It is crucial for my application to be able to select multiple documents at random from a collection in firebase.

Since there is no native function built in to Fireb

8条回答
  •  感情败类
    2020-11-22 10:37

    Unlike rtdb, firestore ids are not ordered chronologically. So using Auto-Id version described by Dan McGrath is easily implemented if you use the auto-generated id by the firestore client.

          new Promise(async (resolve, reject) => {
            try {
              let randomTimeline: Timeline | undefined;
              let maxCounter = 5;
              do {
                const randomId = this.afs.createId(); // AngularFirestore
                const direction = getRandomIntInclusive(1, 10) <= 5;
                // The firestore id is saved with your model as an "id" property.
                let list = await this.list(ref => ref
                  .where('id', direction ? '>=' : '<=', randomId)
                  .orderBy('id', direction ? 'asc' : 'desc')
                  .limit(10)
                ).pipe(take(1)).toPromise();
                // app specific filtering
                list = list.filter(x => notThisId !== x.id && x.mediaCounter > 5);
                if (list.length) {
                  randomTimeline = list[getRandomIntInclusive(0, list.length - 1)];
                }
              } while (!randomTimeline && maxCounter-- >= 0);
              resolve(randomTimeline);
            } catch (err) {
              reject(err);
            }
          })
    

提交回复
热议问题