0

In a Firebase function that is passed a document reference as input, how can I check if that reference is for a document or a collection?

Ex:

if(data.ref instanceof FIRESTORE_COLLECTION_REFERENCE) {
  //do something...
} else if (data.ref instanceof FIRESTORE_DOCUMENT_REFERENCE) {
  //do something else...
}

What is the correct call to that data type if this is an allowable means to check? If not allowed, how can I check this?

Mr.Drew
  • 939
  • 2
  • 9
  • 30

1 Answers1

2

First of all, make sure you have Firebase correctly installed. Now, in order to make it work, you should use the following two imports:

import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.CollectionReference;

Right after that, you can use the following lines of code:

if(data.ref instanceof CollectionReference) {
    //do something...
} else if (data.ref instanceof DocumentReference) {
    //do something else...
}
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • 1
    Thanks for the quick reply! I'll check it out and mark it upon verification, but seems correct. – Mr.Drew Apr 10 '20 at 12:36
  • That's for Android/Kotlin, is this what you need? – Alex Mamo Apr 10 '20 at 12:38
  • Oh wow, nice catch. No, not at all. I'm making a cloud function in JS. Kinda relearning JS and firebase/firestore at the same time. I could just make two different functions and skip the check, but it would be nice to know how. – Mr.Drew Apr 10 '20 at 12:40
  • I found https://firebase.google.com/docs/reference/js/firebase.database.Reference, but I don't see a way to differentiate the two types of references in javascript. – Mr.Drew Apr 10 '20 at 12:47
  • 1
    No, no. That's for Firebase Realtime Database. For Firestore, see [CollectionReference](https://firebase.google.com/docs/reference/js/firebase.firestore.CollectionReference) and [DocumentReference](https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference). – Alex Mamo Apr 10 '20 at 12:53
  • Ah so `instanceof firebase.firestore.CollectionReference` should do the trick? – Mr.Drew Apr 10 '20 at 13:10
  • 1
    This is how [instanceof](https://stackoverflow.com/questions/2449254/what-is-the-instanceof-operator-in-javascript) works in Javascript. I think it might work with the full path or even simpler `data.ref instanceof CollectionReference`. – Alex Mamo Apr 10 '20 at 13:18
  • could you please help me in here: https://stackoverflow.com/questions/66348729/how-to-check-if-a-variable-is-a-firebase-firestore-documentdata-type?noredirect=1#comment117432963_66348729 I have similar problem – sarah Mar 05 '21 at 01:54