Get Random Documents from a Collection in Firebase Firestore with Firebase Cloud Functions


Hello guys, today I will show you how you can get random documents from a collection using Firebase Firestore and Cloud Functions.


Step 1: Generate Random Non-Zero, Non-Duplicate Numbers

First, we'll create a Node.js function that returns an array of random non-zero and non-duplicate numbers. This will generate an array like [3, 5, 2, 4, 1].

const generateRandom = (req, res, next) => {
  const max = 5;
  let random = [];
  for (let i = 0; i < max; i++) {
    let temp = Math.floor(Math.random() * max + 1);
    if (random.indexOf(temp) === -1 && temp !== 0) {
      random.push(temp);
    } else {
      i--;
    }
  }
  req.randomArray = random;
  return next();
};

Step 2: Use Middleware in Your GET Request

Now, we'll use this function as middleware in our main GET request function:

app.get('/getdata', generateRandom, getdata);

Step 3: Define the GET Request Function

Next, define the getdata function:

exports.getdata = (req, res) => {
  let EasySET = [];
  let MediumSET = [];
  let HardSET = [];
  let random = req.randomArray;
  console.log(req.headers);

  Promise.all([
    db.collection('QuestionCollection/Easy/QuestionsData')
      .where('id', 'in', [...random])
      .get()
      .then((snapshot) => {
        snapshot.forEach((document) => {
          EasySET.push(document.data());
        });
      })
      .catch((err) => {
        console.error(err);
        res.status(500).json(err);
      }),
    // Add similar blocks for MediumSET and HardSET if needed
  ]).then(() => {
    res.status(200).json({
      easy: EasySET,
      medium: MediumSET,
      hard: HardSET,
    });
  });
};

In this function, we use the randomArray from our middleware to query Firestore. The where clause allows Firestore to find documents with certain conditions.

For example:

db.collection('QuestionCollection/Easy/QuestionsData')
  .where('id', 'in', [3, 5, 2, 4, 1])
  .get();

This query will search for documents with the id field having values in the array.


Important Note

Ensure that your documents have an auto-incremented id field to make this approach work effectively.