Reputation: 400
In a social app, I have a cloud function that updates a 'likes' counter whenever a post is liked, which is to say whenever the following reference is updated:
/likes/{postId}/{userid}
'countOfLikes' is written at the same level of the wildcard {userId} :
exports.countLikeChange = functions.database.ref('/likes/{postId}/{userid}').onWrite(event => {
const collectionRef = event.data.ref.parent;
var counterRef = collectionRef.child('countOfLikes');
return collectionRef.once('value').then(messagesData => counterRef.set(messagesData.numChildren() - 1));
});
With my current code, when a user like a post, the function is triggered first to update countOfLike, which in turn trigger the same function to do the same action...
Is there a way to specify an exclusion so that the function will not be triggered if {userId} == 'countOfLikes' ?
I know that I could use onCreate instead of onWrite, but you must know that in my app, one user could also remove his 'like'.
Upvotes: 0
Views: 109
Reputation: 598623
There is no way to exclude a specific child from triggering a function.
If you find that need, it typically means you've combined types of data that should be kept separate.
For example, I would expect your like counts to be in a separate node altogether, e.g. /likeCounts/$postId
. If you structure it like that, updating the count for a new like won't retrigger the function.
Upvotes: 2