Following the firebase cloud functions API reference, I am trying to achieve count increase/decrease:
Uploads/
- Posts/
- post_1
- post_2
...
- Likes/
- post_1/
- Number: 4
- post_2/
- Number: 2
...
And,
exports.LikeCount= functions.database.ref('/Posts/{postID}').onWrite(event => {
const Ref = event.data.ref;
const postID = event.params.postID;
const likeCount= Ref.parent.parent.child('/Likes/' + postID + '/Number');
return likeCount.transaction(current => {
if (event.data.exists() && !event.data.previous.exists()) {
return (current || 0) + 1;
}else if (!event.data.exists() && event.data.previous.exists()) {
return (current || 0) - 1;
}
}).then(() => {
console.log("Done");
});
});
Other than locations, it's identical to the example given.
It also gives another example where if the number of likes are deleted, then it recalculates the number of likes (children).
Here is my version (or at least the idea of it) where it checks the number of likes and if it is less than 1, then it recalculates it. (Just because the first function will give 1 regardless of the number of the likes present if the number of likes does not exists).
exports.reCount= functions.database.ref('/Likes/{postID}/Number').onUpdate(event => {
const value = event.data.val;
//If the value is less than 1:
if (value <= 1) {
const currentRef = event.data.ref;
const postID = event.params.postID;
const postRef = currentRef.parent.parent.child('/Uploads/Posts/{postID}/');
return postRef.once('value')
.then(likeData=> currentRef.set(likeData.numChildren()));
}
});
With the second function, I tried to get the Number
value using the following where event.data.val
which gave [Function: val]
in the FB logs, where I thought I would get string value.
...and currentRef.parent.parent.child('/Uploads/Posts/{postID}/').numChilren();
gave TypeError: collectionRef.numChildren is not a function
.
I read tons of online tutorial and API reference but still bit confused to why I can't get the string value.
I guess I am looking for some examples that I can work from.