Reputation: 347
I am trying to deploy the following function to firebase. The function deploys fine, but when the function triggers I get an error: cannot read property 'parent' of undefined
. The error occurs in the first line I reference parent. I used console.log on snapshot and snapshot.ref, and although snapshot exists, snapshot.ref is undefined.
I have used snapshot.ref.parent in other cloud functions and it is working fine. There are two main difference with this function: (a) it is an onUpdate (I have previously been using onCreate and onDelete) (b) it is an async function.
exports.likeRating = functions.database.ref('Ocean/{waveId}/Likes').onUpdate(async (snapshot) =>{
let likes; let dislikes; let comments; let echoes;
await snapshot.ref.parent.child('Dislikes').once('value').then(response=>{dislikes = response.val(); return null});
await snapshot.ref.parent.child('Likes').once('value').then(response=>{likes = response.val(); return null});
await snapshot.ref.parent.child('Comments').child('CommentsCount').once('value').then(response=>{comments = response.val(); return null});
await snapshot.ref.parent.child('Echoes').once('value').then(response=>{echoes = response.val(); return null});
snapshot.ref.parent.child('Rating').set(dislikes+likes+comments+echoes);
return null;
}
Any ideas as to why I am getting this error? All help is appreciated.
Upvotes: 0
Views: 361
Reputation: 66355
That function will run significantly slower than it needs to as you're waiting for your requests in series, you should await a Promise.all([<Promises>])
instead, also the return null
is redundant.
I'm also not sure why you add everything up each time instead of incrementing the Rating value but maybe I didn't think about it as much as you.
If you look at the docs the signature of the callback is function(non-null functions.Change containing non-null functions.firestore.DocumentSnapshot, optional non-null functions.EventContext)
So the first param is change which contains before
and after
which are of type DocumentSnapshot
, it is those properties you should be using e.g. change.after.ref
.
Upvotes: 1