How to get a random document from Firebase Cloud Firestore with Ionic Angular

I am currently in the midst of building this app and I was Googling to find a way to get a random document from Cloud Firestore. Knowing the cool features of Firebase and Cloud Firestore, surely there is an easy method to do this. However…

RYMS
RYMS
May 13 · 5 min read

I was not able to find any method that could achieve this with Ionic Angular. Don’t believe me, go ahead and try to look for it. So, I decided to write a guide for developers that would want to pull a random document from a collection from Firebase Cloud Firestore using Ionic Angular

First off, I just want to say, it is very surprising for me to find out but there are no official guide on doing this. One would expect someone would have written a simple guide about this by now, but trust me, I could not find it. I found one solution on Stack Overflow, which I have adapted to be used with Ionic Angular, particularly, TypeScript, which I would detail in this article.

Image for post
Image for post
Photo by Patrick Fore on Unsplash

But first, before I go ahead and show you the method, just a brief explanation of what is Firebase and what is Firebase Cloud Firestore, just in case you have stumbled upon this article and would like to learn more about the subject matter.

Firebase is a mobile and web application development platform developed by Firebase, Inc. in 2011, then acquired by Google in 2014. As of March 2020, the Firebase platform has 19 products, which are used by more than 1.5 million apps-

From Wikipedia

One of the 19 products on offer by Firebase is a fully featured, query-able NoSql database called Cloud Firestore.

Cloud Firestore is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud Platform. Like Firebase Realtime Database, it keeps your data in sync across client apps through realtime listeners and offers offline support for mobile and web so you can build responsive apps that work regardless of network latency or Internet connectivity. Cloud Firestore also offers seamless integration with other Firebase and Google Cloud Platform products, including Cloud Functions.

From Firebase website

To find out more about Firebase, Cloud Firestore and other products related to Firebase, please visit the Firebase website here

Pulling random data from Cloud Firestore, a high level overview

On a very high level overview, you need to have an incremental or randomised ID number inside your document.

Your data should look something like this:

Image for post
Image for post
DIAGRAM 1: SHOWING INCREMENTAL ID INSIDE DOCUMENT

“But I did not add an incremental or randomised ID inside my document, and I have over 1000+ entries. How do I add this into each document?”

Don’t worry, I was in the same boat, so I decided to write something to assist me with that problem. The solution is to build a simple Firebase Function that would automatically do this for you. You can use this simple snippet of code that I have written which would add and update the field id into each document through the for loop.

const admin = require("firebase-admin");admin.initializeApp(functions.config().firebase);...exports.updateRandom=functions.https.onRequest((request, response) => {
admin
.firestore()
.collection("user")
.get()
.then(res => {
var pack_data = [];
res.forEach(datax => {
pack_data.push({id: datax.id});
});
for(var x=0;x<pack_data.length;x++)
{
var random=Math.floor((Math.random() * pack_data.length) + 1);
admin
.firestore()
.collection("user")
.doc(pack_data[x].id)
.update({id:random})
}
return response.send("OK");
})
.catch(err=>{
return response.send("ERROR "+err);
})
})

So now that we have added a randomised id all we need to do is to generate a random number and query that random number from the Cloud Firestore.

Pulling a user document randomly

For example, let’s say we are building a raffles draw app and we need are going to pull a random user document from a collection of users inside the Cloud Firestore. Assuming that we have added a randomised or incremental ID field inside each document, the next step would be doing the query.

Step 1: Generate a Random Number

On the client side application, we will need to generate a random number. This random number will be the key that will be referenced when we are pulling a randomised document from the Cloud Firestore.

Assuming that we have over 1500 users, we can get a randomised number between 0 to 1499 (Remember, programmers count from 0) users by using this snippet of code:

var random=Math.floor((Math.random() * documentSize.length));

Step 2: Querying The Random Number

Once we have a generated a random number, we can then query the Cloud Firestore within our client side application. We need to write a function that will do this. In this case, let’s called our function getRandomUser():

getRandomUser(){return new Promise(async (resolve)=>{var random = Math.floor((Math.random() * documentSize.length));await firebase
.firestore()
.collection("user")
.where("id",">=" , random)
.limit(1)
.get()
.then((res)=>{
let pack_data:any=[];
res.forEach(quest=>{
pack_data.push(quest.data());
});
resolve(pack_data[0]);})}

If you notice the .where statement is where we actually query the database to return the same number or greater than the random number we have generated. This should return the closest item to the random number even if the random generated number do not return a document.

Although this method is doing a single directional query, the same approach can be made if you want to do a bi directional method, which I will not cover here, because using this single directional method returns the random item that I am looking for just fine, but I just want to note that it is possible to do a bi directional method.

Step 3: Getting The Random Document

The query from the method in the previous section resolves a promise and returns pack_data[0]. This would be the random document that we want and we can then use this in our application.

Summary

If you are able to complete the 3 tasks above, you should be able to return and get a randomise document from your Cloud Firestore. Do give it a try.

Happy coding!

Suggested Enhancements

  1. As mentioned above, you can add a bidirectional approach to the query
  2. You can add another extra layer of randomness if more than 1 document was returned. We have set limit to 1 in the above document with limit(1) but we can return limit to 5 and randomise even further with the 5 returned documents.

A note from the Plain English team

Did you know that we have four publications? Show some love by giving them a follow: JavaScript in Plain English, AI in Plain English, UX in Plain English, Python in Plain English — thank you and keep learning!

Also, we’re always interested in helping to promote good content. If you have an article that you would like to submit to any of our publications, send an email to submissions@plainenglish.io with your Medium username and what you are interested in writing about and we will get back to you!

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store