Firestore: How to get random documents in a collection

后端 未结 8 1724
旧巷少年郎
旧巷少年郎 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:29

    Posting this to help anyone that has this problem in the future.

    If you are using Auto IDs you can generate a new Auto ID and query for the closest Auto ID as mentioned in Dan McGrath's Answer.

    I recently created a random quote api and needed to get random quotes from a firestore collection.
    This is how I solved that problem:

    var db = admin.firestore();
    var quotes = db.collection("quotes");
    
    var key = quotes.doc().id;
    
    quotes.where(admin.firestore.FieldPath.documentId(), '>=', key).limit(1).get()
    .then(snapshot => {
        if(snapshot.size > 0) {
            snapshot.forEach(doc => {
                console.log(doc.id, '=>', doc.data());
            });
        }
        else {
            var quote = quotes.where(admin.firestore.FieldPath.documentId(), '<', key).limit(1).get()
            .then(snapshot => {
                snapshot.forEach(doc => {
                    console.log(doc.id, '=>', doc.data());
                });
            })
            .catch(err => {
                console.log('Error getting documents', err);
            });
        }
    })
    .catch(err => {
        console.log('Error getting documents', err);
    });
    

    The key to the query is this:

    .where(admin.firestore.FieldPath.documentId(), '>', key)
    

    And calling it again with the operation reversed if no documents are found.

    I hope this helps!
    If interested, you can find this specific part of my API on GitHub

提交回复
热议问题