Firebase functions - Counting children and updating an entry


Firebase functions - Counting children and updating an entry



I have been trying to use Firebase Functions to write a simple method, but I am unfamiliar with JS.



Below is the structure of my Realtime Database



-spots



---is_hidden: false



---likes



------like_id_1: true



---dislikes



------dislike_id_1: true



I am trying to write a simple method that does the following: Whenever an entry is added to dislikes, count the likes and the dislikes.



If the number of dislikes is larger than the number of ( likes + 5 ),
change the value of is_hidden to true



This is my attempt to solving the problem


exports.checkHiddenStatus = functions.database.ref('/spots/{spotid}').onWrite(
(change, context) => {
const collectionRef = change.after.ref;
const isHiddenRef = collectionRef.child('is_hidden');
const likesRef = collectionRef.child('likes');
const dislikesRef = collectionRef.child('dislikes');


if(isHiddenRef.before.val()) return;

let likeCount = likesRef.numChildren();
let dislikeCount = dislikesRef.numChildren();

let isHidden = false;

if( dislikeCount >= (likeCount + 5))
isHidden = true;

if(!isHidden) return;

// Return the promise from countRef.transaction() so our function
// waits for this async event to complete before it exits.
return isHiddenRef.transaction((current) => {
return isHidden;
}).then(() => {
return console.log('Counter updated.');
});
});



Sadly, because I have no experience with JS I keep getting stuck with error messages I don't understand. The most recent being



TypeError: Cannot read property 'val' of undefined
at exports.checkHiddenStatus.functions.database.ref.onWrite (/user_code/index.js:28:28)



Can somebody please help me write this function? Thank you!





FYI the error message is saying that the problem is on line 28 of index.js.
– Doug Stevenson
Jul 2 at 19:57




1 Answer
1



It looks like you're trying to treat a database Reference object like a Change object. Change has before and after properties, but a reference does not.


before


after



If you have a database reference object, and you want the value of the database at that location, you need to query it with its once() method.



Read more about reading and writing data using the Admin SDK.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

Display dokan vendor name on Woocommerce single product pages