4

I am trying to get some random posts from Firebase. But i am unable to get random document id.

Is there any way to retrieve data from Firebase like this :-

  getRandomData() async {
QuerySnapshot snapshot = await posts
    .document(random.id)
    .collection('userPosts')
    .getDocuments();}

i am trying to say that. Now i am able to get documentID normally not in italics.so now how can i get random documentID from Firebase.

enter image description here

Chinmaya Garnaik
  • 83
  • 1
  • 2
  • 7

4 Answers4

3

List documentIds in a list first.

var list = ['documentId1','documentId2','documentId3'];

var element = getRandomElement(list);

Then query the documentSnapshot

Subair K
  • 1,760
  • 1
  • 11
  • 31
2

You can first get all documents in you collection.

Try this code:

async getMarker() {
    const snapshot = await firebase.firestore().collection('userPosts').get();
    const documents = [];
    snapshot.forEach(doc => {
       documents[doc.id] = doc.data();
    });
    return documents;
}

Next, from return documents you can create a list of documents id and get random numbers (document id) from this list.

Julien J
  • 2,826
  • 2
  • 25
  • 28
Captivity
  • 279
  • 5
  • 21
1

The main problem here that's going to prevent you from moving forward is the fact that you don't actually have any documents nested immediately under "posts". Notice that the names of the documents are in italics. That means there isn't actually a document here at all. The reason why they are show, however, is because you have a subcollection "userPosts" nested under the path where that document ID exists.

Since you don't have any documents at all under "posts", the usual strategies to find a random document won't work at all. You're going to have to actually populate some data there to select from, or find another way to select from the data in the subcollections.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • So what you are saying that if I change my code to default generator. I mean if I remove the Italics then I can get random posts.if possible then how. – Chinmaya Garnaik Aug 07 '20 at 17:49
  • I'm really not sure what your comment is suggesting. I'm saying you don't have any documents here at all to select from. You will need to create documents, then use the linked method to find a random one. – Doug Stevenson Aug 07 '20 at 18:47
  • i am trying to say that. Now i am able to get documentID normally not in italics.so now how can i get random documentID from Firebase.https://i.stack.imgur.com/Z3UW4.png – Chinmaya Garnaik Aug 09 '20 at 07:58
0

firestore() .collection('SOURCE') .doc(props?.route?.params?.data?.id) .collection('userPosts') .get() .then(querySnapshot => { querySnapshot.forEach(documentSnapshot => { console.log('User ID: ', documentSnapshot.id, documentSnapshot.data()); }) })

Nikhil Dangi
  • 289
  • 3
  • 4