0

I'm trying to figure out how to console.log random documents from firestore. I've looked through Get nth document in a collection in Firestore, Select random document from Firestore, Firestore: How to get random documents in a collection, Get random documents from Firestore using Javascript, https://javascript.plainenglish.io/how-to-get-a-random-document-from-firebase-cloud-firestore-with-ionic-angular-a59940efb55e. I formatted some of these into vanilla js but nothing worked, got the # of docs in firestore and printed random numbers from that amount but got stuck after that. Is there some way to at least get the nth document in firestore or another way to get random documents?

The furthest I got was this which gets the number of docs in the collection, and picks 10 'numbers/orders' from it, and prints them.

firebase.firestore().collection('user').get().then(function(doc) {
  size = doc.size 
  for(let i=0;i<10;i++){
  var random = Math.floor((Math.random() * size));
   firebase.firestore().collection("userInfo").where("userId",">=",random).get().then((querySnapshot) => {
//     querySnapshot.forEach((doc) => {
//         console.log(doc.data());
//     });
//  })
Anteos1
  • 99
  • 1
  • 10
  • From the various solutions in the questions you have linked and their linked duplicates, in your question, please cover **how** they aren't working for you. What code are you currently using? What does your database look like? How many documents are in the collection? Are you getting any documents when querying for a random one? What results are you getting at the moment and why aren't they suitable? – samthecodingman Aug 06 '21 at 17:40
  • Gotcha, only 25 docs, the most I could get it to do was print 10 'document numbers' (1st,4th etc) using firebase.firestore().collection('userInfo').get().then(function(doc) { size = doc.size //for(let i=0;i<10;i++){ var random = Math.floor((Math.random() * size)); // firebase.firestore().collection("userInfo").where("userId","!=",random).get().then((querySnapshot) => { // querySnapshot.forEach((doc) => { // console.log(doc.data()); // }); // }) – Anteos1 Aug 06 '21 at 17:54
  • Hi, it would be really helpful if you edit your question and show us how your firestore database looks like. What kind off data are you storing? And also you are using two collections in the question, "user", "userInfo", and in the comments section you have used only userInfo, give us a clarity regarding this too. – Zeenath S N Aug 23 '21 at 13:29

0 Answers0