I don’t understand why I’m getting this error for the code below.
Typescript: Property ‘size’ does not exist on type ‘never’
The error is pointing to friendRef.size
.
It is also giving an error on friendRef.update
:
Property ‘update’ does not exist on type ‘never’
How do I properly run a WHERE
clause query on a collection that will only ever return either 1 or 0 records and then update some of its properties?
export const onRespondedToFriendRequest = functions.firestore
.document("users/{userDocID}/notifications/{notifID}")
.onUpdate(async (change, context) => {
const notifID = context.params.notifID;
const uid = context.params.userDocID; // user A
const beforeData = change.before.data();
const afterData = change.after.data();
const friendUID = afterData.uid; // user B (the friend)
// If notifID is "2" and moveOnToNextStep = true
if (notifID === "2" && afterData.moveOnToNextStep) {
const friendsQuerySnapshot = await fs
.collection("users/" + friendUID + "/friends")
.where("uid", "==", uid)
.limit(1)
.get();
let friendRef;
friendsQuerySnapshot.forEach((friendDoc) => {
friendRef = friendDoc.ref;
});
if (friendRef && friendRef.size !== 0) { // ERROR HERE
await friendRef.update({ // ERROR HERE
stat: "1",
modifiedDate: Math.floor((new Date).getTime()/1000).toString(),
});
}
}
});
2
Answers
set type for
friendRef
:Your code doesn’t handle the case where there are no results. In that case
friendRef
will beundefined
(its default value), and you can’t callsize
orupdate
on that.The simplest fix is to check for an empty result first, and only then have the rest of your code:
At this point you actually also don’t need the loop anymore, and can just do: