In Firebase Cloud Firestore, I have "user_goals" in collections and goals may be a predefined goal (master_id: "XXXX") or a custom goal (no "master_id" key)
In JavaScript, I need to write two functions, one to get all predefined goals and other to get all custom goals.
I have got some workaround to get custom goals by setting "master_id" as "" empty string and able to get as below:
db.collection('user_goals') .where('challenge_id', '==', '') // workaround works .get()
Still this is not the correct way, I continued to use this for predefined goals where it has a "master_id" as below
db.collection('user_goals') .where('challenge_id', '<', '') // this workaround .where('challenge_id', '>', '') // is not working .get()
Since Firestore has no "!=" operator, I need to use "<" and ">" operator but still no success.
Question: Ignoring these workarounds, what is the preferred way to get docs by checking whether a specific field exists or does not exists?
There are three ways to retrieve data stored in Cloud Firestore. Any of these methods can be used with documents, collections of documents, or the results of queries: Call a method to get the data once. Set a listener to receive data-change events.
Collections and documents are created implicitly in Cloud Firestore. Simply assign data to a document within a collection. If either the collection or document does not exist, Cloud Firestore creates it.
A DocumentReference refers to a document location in a Firestore database and can be used to write, read, or listen to the location. The document at the referenced location may or may not exist. A DocumentReference can also be used to create a CollectionReference to a subcollection.
Is there any way to get the last created document in Firebase Firestore collection? Yes, there is! The simplest way to achieve this is to add a date property to each object in your collection, then simply query it according to this new property descending and call limit(1) function. That's it!
As @Emile Moureau solution. I prefer
.orderBy(`field`)
To query documents with the field exists. Since it will work with any type of data with any value even for null
.
But as @Doug Stevenson said:
You can't query for something that doesn't exist in Firestore. A field needs to exist in order for a Firestore index to be aware of it.
You can't query for documents without the field. At least for now.
The preferred way to get docs where a specified field exists is to use the:
.orderBy(fieldPath)
As specified in the Firebase documentation:
Thus the answer provided by @hisoft is valid. I just decided to provide the official source, as the question was for the preferred way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With