My FireBase Learnings

Header Image

1. Get FireStore data from a Cloud Function

First, initialize admin and db.

This should only be done once. Preferably in the root function file.

const functions = require('firebase-functions');
const admin = require('firebase-admin');


const db = admin.firestore();

Exported code,

exports.getData = functions.https.onRequest((req, res) => {
	const docRef = db.collection('collection name').doc('document name');
	const getDoc = docRef.get()
	  .then(doc => {
	    if (!doc.exists) {
	      console.log('No such document!');
	      return res.send('Not Found')
	      return res.send(;
	  .catch(err => {
	    console.log('Error getting document', err);

That's it 😄 !

2. Get a random element from a FireStore collection

Firstly, get the collection data in a variable :

const unassigned = db

const data = await unassigned.get();

Then loop over the data, while storing current document id in a temporary variable :

let temp;
data.forEach(doc => {
	temp =;

That's it ! You get a random Document in your variable. This is not the way you should do it, however Firebase has no way to select random documents from a collection, so this has to do 😕.

Buy Me A Coffee

Get in touch !!

Github LinkedIn Twitter