I have products that evrey product have children and evrey child have children and i want to collect the sum for evrey product

my code is:
var firebaseProductsCollection = database.ref().child('finalVerifoneProducts');
firebaseProductsCollection.on('value', function(products) {
products.forEach(function(firebaseProductReference) {
code = firebaseProductReference.key;
products.forEach(function(firebaseProductReference) {
var code = firebaseProductReference.key;
var firebaseGetBarcodes = database.ref().child('finalVerifoneProducts').child(code);
firebaseGetBarcodes.on('value', function(productsBarcodes) {
productsBarcodes.forEach(function(firebaseProductReference2) {
var product = firebaseProductReference2.val();
if (!productArray.includes(product.code)) {
// we have new product
console.log(product.code + " : " + totalSum);
productArray.push(product.code);
totalSum = product.sum;
} else {
totalSum = parseInt(totalSum) + parseInt(product.sum);
} // close the else
But the quantity of the first product is always 0 and the rest of the products gets wrong
When you load a path from the database, all data under that path is already included in the snapshot you get back. So there's no need to separate load the nested child data.
Knowing that, you can significantly simplify your code to:
const firebaseProductsCollection = database.ref().child('finalVerifoneProducts');
firebaseProductsCollection.on('value', function(products) {
let totalSum = 0; // ๐
products.forEach(function(productSnapshot) {
code = productSnapshot.key;
productSnapshot.forEach(function(productChildSnapshot) {
var product = productChildSnapshot.val();
totalSum += product.sum;
});
});
console.log(totalSum); // ๐
});