I have to get different values from different children at the same ref. In Swift I would do:
var sum = 0
var totalPosts = 0
var starRating = 0 // run some calculations on totalPosts + sum
let sneakersRef = Database.database().reference().child("sneakers").child(adidas_ABC) // postId
sneakersRef.observeSingleEvent(of: .value, with: { (snapshot) in
if !snapshot.exists() { return }
if snapshot.hasChild("postCount") {
let childSnapshot = snapshot.childSnapshot(forPath: "postCount")
if let postCount = childSnapshot.value as? Int {
self.totalPosts = postCount
}
}
}
if snapshot.hasChild("fans") {
let childSnapshot = snapshot.childSnapshot(forPath: "fans")
for child in childSnapshot.children {
let userId = child as! DataSnapshot
for snap in userId.children {
guard let dict = snap.value as? [String:Any] else { continue }
let price = dict["price"] as? Int ?? 0
self.sum += price
}
// update ref with value obtained from sum and create/update a starRating
}
}
})
How would I do the same thing in Cloud Functions? The code inside the childSnapshot.forEach((child) => { }
below is what I need help with.
exports.updateValues = functions.https.onCall((data, context) => {
const postId = data.postId; // adidas_ABC
var sum = 0;
var totalPosts = 0;
var starRating = 0;
const sneakersRef = admin.database().ref('sneakers').child(postId);
sneakersRef.once('value', snapshot => {
if (snapshot.exists()) {
const postCount = snapshot.child("postCount").val();
totalPosts = postCount
const childSnapshot = snapshot.child("fans").val().userID;
// the code in this loop is questionable
childSnapshot.forEach((snap) => {
const price = snap.child("price").val();
sum += price
})
// run calculations to get starRating
return sneakersRef.update({ "sum": sum, "starRating": starRating }).then(() => {
})
.catch((error) => {
console.log('something went wrong: ', error);
});
} else {
console.log('doesn't exist');
}
});
});
Here is my db layout:
@sneakers
@adidas_ABC // same postId for anything dealing with adidas
@fans // this might not exist in which case postCount would be zero
@userId_XYZ
@postId_123
-condition: "used"
-price: 100
-type: shell_top
@postId_456
-condition: "new"
-price: 500
-type: yeezy
-fanCount: 1
-postCount: 2
-sum: 600
-starRating: 4