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

0

4 Answers 4

3

List documentIds in a list first.

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

var element = getRandomElement(list);

Then query the documentSnapshot

Sign up to request clarification or add additional context in comments.

Comments

2

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.

3 Comments

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.
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.
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.i.sstatic.net/Z3UW4.png
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.

Comments

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()); }) })

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.