0

I am writing supporting method in firebase function. I need to get only random company name from the companies collections rather the given company where I getting only first value from the collection.

Any suggestion would be helpful.

async function selectCompany(companyName) {
  const vouchercompany = [];
  try {
    await db.collection('companies')
      .where('companyName', '!=', companyName)
      .get()
      .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          vouchercompany.push(doc.data())
        })
      })
    return vouchercompany;
  } catch (error) {
    json(error.message)
  }
}
Irfana
  • 21
  • 1
  • 5

1 Answers1

1

Ideally, you should have a master document that contains an array of all company names and their relevant document ID or relevant collection name.

Create a Firestore document "_index" inside your companies collection as a master index

companies/_index
      // (keep a total count of all companies, helpful if you need to scale over 10k companies)
      count: 1200,
      // (An array can hold multiple items without breaking a sweat)
      companyIndex: [companyName + : + documentID]

Simple read the document and iterate over the companyIndex item. once you have picked your random items, you can split it with:

const value = item.split(':');
const companyName = value[0];
const docReference = value[1];

to add a company, you can use arrayUnion with [companyName, documentId].join(':') you can find the relevant methods to update arrays here.

This allows you to make more dynamic and randomized results without any of the problems existing random solutions have. That being said, I would not use this for something with documents in the potential millions such as user posts or comments.

DIGI Byte
  • 4,225
  • 1
  • 12
  • 20