Filter by user email then aggregate the result (Solved)

I created a collection named PointsHistory where list out each member’s point activity, including the number of points they earn and spend, date, and activity description. In each member’s profile, I would like them to see their total current points. My difficulty is that I couldn’t get the correct aggregation output. My code is as below. It would be greatly appreciated if anyone can help. I have been struggling on this for 2 days.

import wixUsers from ‘wix-users’;
import wixData from ‘wix-data’;

$w.onReady(() => {
Sum_pointsSpend();

});
export function Sum_pointsSpend() {

let user = wixUsers.currentUser;
let userId = user.id;
user.getEmail()
.then( (email) => {
let userEmail = email;

wixData.aggregate("PointsHistory") 
    .group('email') 
    .sum("pointsSpend", "sumpointsSpend")   

// pointsSpend is the point that member earn/spend by each activity
.run()
.then( (results) => {

        $w('#TotalPoints').value = results.items[0].sumpointsSpend; 

// TotalPoints is the text box to display current total points of each member in each own member page
} );} );

}

#filter #Aggregate

By using console.log(results), I realized that my aggregation results had been grouped by user email successfully. However, I couldn’t let it display the correct group result based on each user email. Now it always display the result of item[0]. How can I display the result based on different item without human input?

I changed to reference ID instead of email, and changed the code as follows. Then it works :

import wixUsers from ‘wix-users’;
import wixData from ‘wix-data’;
import wixLocation from ‘wix-location’;

let user = wixUsers.currentUser;
let userId = user.id;
user.getEmail()
.then( (email) => {
let userEmail = email;

} );

$w.onReady(() => {
Sum_pointsSpend();

});

export function Sum_pointsSpend() {

let filter = wixData.filter().eq(“title”, userId);
// In PointsHistory dataset the “title” column value is from privatememberdata userId field)
console.log(filter); // This is to help you figure out if the wanted item had been filtered out
wixData.aggregate(“PointsHistory”)
.filter(filter)
.sum(“pointsSpend”, “sumpointsSpend”)
.run()
.then( (results) => {

        $w('#TP').value = results.items[0].sumpointsSpend;  // TP is the text box showing sum 
    console.log(results);    

} );
}

#filter #Aggregate

1 Like