Reputation: 2035
Saw that firebase added functions, so I have been attempting to bring them to use..
Here is how my data is structured:
-feed1
--child count = 0
--childs
---1
---2
---3
-feed2
--child count = 0
--childs
---1
---2
---3
-feed3
--child count = 0
--childs
---1
---2
---3
My goal is for each feed object to be able to count how many children that each 'childs' field has an update the child count field with how many each have.
Here is what I have so far.. I tested it by adding a child object and that didn't seem to trigger the function. I suspect that it has something to do with the wildcard element of it but can't really figure out how to do it
var functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.countParent = functions.database.ref('{schoolid}/childs').onWrite(event => {
return event.data.ref.parent().child('childCount').set(event.data.numChildren());
});
Any ideas?
Upvotes: 0
Views: 734
Reputation: 6981
Check your error logs in the Firebase Console, I bet you'll see an error there.
Parent is a property, not a function.
Even if you fix the errors in your function, it would be error prone. numChildren()
is inefficient and you should use a transaction.
I modified the working code from our Child Count example on Github for your schema:
exports.countParent = functions.database.ref("{schoolid}/childs/{childid}").onWrite(event => {
var collectionRef = event.data.ref.parent;
var countRef = collectionRef.parent.child('childCount');
return countRef.transaction(function(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;
}
});
});
That should be a good starting point.
Upvotes: 1