Firestore: How to get random documents in a collection

后端 未结 8 1848
旧巷少年郎
旧巷少年郎 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 10:40

    The other solutions are better but seems hard for me to understand, so I came up with another method

    1. Use incremental number as ID like 1,2,3,4,5,6,7,8,9, watch out for delete documents else we have an I'd that is missing

    2. Get total number of documents in the collection, something like this, I don't know of a better solution than this

       let totalDoc = db.collection("stat").get().then(snap=>snap.size)
      
    3. Now that we have these, create an empty array to store random list of number, let's say we want 20 random documents.

       let  randomID = [ ]
      
       while(randomID.length < 20) {
           const randNo = Math.floor(Math.random() * totalDoc) + 1;
           if(randomID.indexOf(randNo) === -1) randomID.push(randNo);
       }
      

      now we have our 20 random documents id

    4. finally we fetch our data from fire store, and save to randomDocs array by mapping through the randomID array

       const  randomDocs =  randomID.map(id => {
           db.collection("posts").doc(id).get()
               .then(doc =>  {
                    if (doc.exists) return doc.data()
                })
               .catch(error => {
                    console.log("Error getting document:", error);
               });
         })
      

    I'm new to firebase, but I think with this answers we can get something better or a built-in query from firebase soon

提交回复
热议问题