Given a given Firestore path what's the easiest and most elegant way to check if that record exists or not short of creating a document observable and subscribing to it?
Cloud Firestore doesn't support native indexing or search for text fields in documents. Additionally, downloading an entire collection to search for fields client-side isn't practical. To enable full text search of your Cloud Firestore data, use a dedicated third-party search service.
Remember, all paths in Cloud Firestore follow the pattern of collection / document / collection / document / etc. So if you remove the last part of your function and just have: docRef = Firestore.firestore().document("userData/scriptureTracking/users/" + user_id.replacingOccurrences(of: " ", with: "_"))
Taking a look at this question it looks like .exists
can still be used just like with the standard Firebase database. Additionally, you can find some more people talking about this issue on github here
The documentation states
NEW EXAMPLE
var docRef = db.collection("cities").doc("SF"); docRef.get().then((doc) => { if (doc.exists) { console.log("Document data:", doc.data()); } else { // doc.data() will be undefined in this case console.log("No such document!"); } }).catch((error) => { console.log("Error getting document:", error); });
OLD EXAMPLE
const cityRef = db.collection('cities').doc('SF'); const doc = await cityRef.get(); if (!doc.exists) { console.log('No such document!'); } else { console.log('Document data:', doc.data()); }
Note: If there is no document at the location referenced by docRef, the resulting document will be empty and calling exists on it will return false.
OLD EXAMPLE 2
var cityRef = db.collection('cities').doc('SF'); var getDoc = cityRef.get() .then(doc => { if (!doc.exists) { console.log('No such document!'); } else { console.log('Document data:', doc.data()); } }) .catch(err => { console.log('Error getting document', err); });
If the model contains too much fields, would be a better idea to apply a field mask on the CollectionReference::get()
result (let's save more google cloud traffic plan, \o/). So would be a good idea choose to use the CollectionReference::select()
+ CollectionReference::where()
to select only what we want to get from the firestore.
Supposing we have the same collection schema as firestore cities example, but with an id
field in our doc with the same value of the doc::id
. Then you can do:
var docRef = db.collection("cities").select("id").where("id", "==", "SF"); docRef.get().then(function(doc) { if (!doc.empty) { console.log("Document data:", doc[0].data()); } else { console.log("No such document!"); } }).catch(function(error) { console.log("Error getting document:", error); });
Now we download just the city::id
instead of download entire doc just to check if it exists.
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