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?
7 Answers
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);
});

- 6,594
- 3
- 39
- 62
-
Thanks for that! I think your answer has some omissions though? – David Haddad Nov 15 '17 at 13:35
-
What do you mean? Is there a use case I'm missing or something? – DoesData Nov 15 '17 at 13:53
-
I meant the code doesn't add up the way you wrote it. Maybe some things got lost when you were pasting it. – David Haddad Nov 15 '17 at 13:56
-
Yeah that would be because I looked at the Swift code since I do iOS. I updated my answer to have JavaScript so it matches your question. – DoesData Nov 15 '17 at 14:47
-
3Is the get function deprecated? – Sireini Apr 17 '18 at 11:20
-
the `Get()` function is still used in Google Documentation as of 9-9-19 so I don't think it's deprecated. – DoesData Sep 09 '19 at 15:15
-
2This answer is no longer valid. When I use it, the get function returns an observable and not a promise. You need to add docRef.ref.get – Joshua Foxworth Jul 30 '20 at 14:18
-
Thank you a lot for answer, it is very helpful. Do you maybe know how to check if value in document exists? – helloitsme2 Oct 30 '20 at 07:52
-
@JoshuaFoxworth In what version of firebase are you getting an observable from `get`? I would love that. Half my code is converting snapshots to observables... https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference#get – nicholas Mar 04 '21 at 15:38
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.

- 181
- 2
- 4
-
2Does that really work? I am trying to find the `select()` method under [Collection Reference](https://firebase.google.com/docs/reference/js/firebase.firestore.CollectionReference) and I couldn't find it. – cbdeveloper May 27 '20 at 09:24
-
2@cbdeveloper, [Collection Reference](https://firebase.google.com/docs/reference/js/firebase.firestore.CollectionReference) inherits [Query
](https://firebase.google.com/docs/reference/js/firebase.firestore.Query) which one have the ```select()``` method. But the documentation doesn't show it :(. You can find it on the source code [reference.ts](https://github.com/googleapis/nodejs-firestore/blob/master/dev/src/reference.ts). – ch4k4uw May 28 '20 at 15:44
Check this :)
var doc = firestore.collection('some_collection').doc('some_doc');
doc.get().then((docData) => {
if (docData.exists) {
// document exists (online/offline)
} else {
// document does not exist (only on online)
}
}).catch((fail) => {
// Either
// 1. failed to read due to some reason such as permission denied ( online )
// 2. failed because document does not exists on local storage ( offline )
});

- 331
- 1
- 7
2022 answer: You can now use the count()
aggregation to check if a document exists without downloading it.
Here is a TypeScript example:
import { getCountFromServer, query, collection, documentId } from '@firebase/firestore'
const db = // ...
async function userExists(id: string): Promise<boolean> {
const snap = await getCountFromServer(query(
collection(db, 'users'), where(documentId(), '==', id)
))
return !!snap.data().count
}

- 2,048
- 2
- 17
- 13
I Encountered Same Problem recently while using Firebase Firestore and i used following approach to overcome it.
mDb.collection("Users").document(mAuth.getUid()).collection("tasks").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
if (task.getResult().isEmpty()){
Log.d("Test","Empty Data");
}else{
//Documents Found . add your Business logic here
}
}
}
});
task.getResult().isEmpty() provides solution that if documents against our query was found or not

- 795
- 7
- 19
Depending on which library you are using, it may be an observable instead of a promise. Only a promise will have the 'then' statement. You can use the 'doc' method instead of the collection.doc method, or toPromise() etc. Here is an example with the doc method:
let userRef = this.afs.firestore.doc(`users/${uid}`)
.get()
.then((doc) => {
if (!doc.exists) {
} else {
}
});
})
Hope this helps...

- 3,893
- 5
- 46
- 77
If for whatever reason you wanted to use an observable and rxjs in angular instead of a promise:
this.afs.doc('cities', "SF")
.valueChanges()
.pipe(
take(1),
tap((doc: any) => {
if (doc) {
console.log("exists");
return;
}
console.log("nope")
}));

- 3,893
- 5
- 46
- 77