I'm looking for how to check if a documents exists in my cloud functions My functions belows works fine when just incrementing an existing value, but now I'm trying to add functionality where it checks to see if the previous value exists and if it doesn't set as 1.
I've tried a different methods but I get things like "snapshot.exists" or "TypeError: Cannot read property 'count' of undefined at docRef.get.then.snapshot
var getDoc = docRef.get()
.then(snapshot => {
if (typeof snapshot._fieldsProto.count !== undefined) {
console.log("haha3", snapshot._fieldsProto.count)
var count = Number(jsonParser(snapshot._fieldsProto.count, "integerValue"));
docRef.set({
count: count + 1
});
}
else {
docRef.set({
count: 1
});
}
});
below is the code for the exists() error
var getDoc = docRef.get()
.then(snapshot => {
if snapshot.exists() {
console.log("haha3", snapshot._fieldsProto.count)
var count = Number(jsonParser(snapshot._fieldsProto.count, "integerValue"));
docRef.set({
count: count + 1
});
}
else {
docRef.set({
count: 1
});
}
});
The error for this code is:
TypeError: snapshot.exists is not a function at docRef.get.then.snapshot
It seems like
docRef
either points to a collection or is a query. In that case yoursnapshot
is of typeQuerySnapshot
.To check if a query has any result, use
QuerySnapshot.empty
.I kept getting errors saying either empty or exists were not functions (tried many iterations) so eventually I landed on just using an undefined check and it works perfectly.
It turns out the problem is much simpler than I imagined:
DocumentSnapshot.exists
is a read-only property, not a function. So the proper way to use it is: