There are several issues that will cause you grief. First you need to check to ensure that the values you are summing are in fact summing valid data.
You should test to ensure that you got a valid sum returned. Second when you call the function, you need to wait for the result, because of the promise ( a promise that data will be returned at some point) being returned by the WixData.aggregate(). The await causes a pause in the code until the promise is fullfilled (the data is ready, summed etc. ) and the data results are returned. Then the code continues executing.
Remember the function where you call GetAllSumVotes(), must also have the async in front of it as well, since you are using the await, when calling GetAllSumVotes().
I have cleaned up your code and posted the changes/corrections below. Remember to use a .catch() with your .then(), when using WixData. This best practice will help you catch errors when querying data that might not be there. Also, always return a default value in your catch() as well. This way your website page won’t break when it hits the catch(). Often people will put in a catch, but not return anything. Unfortunately, your calling code often is expecting a value to be returned, and this is a way to avoid it from breaking. Often people using your website won’t be using a console and won’t see the error message from the catch(). This will silently allow your code to continue. You will of course have to deal with it in your calling code.
export async function GetAllSumVotes() {
return wixData.aggregate("Competition")
.sum("votes")
.run()
.then( (results) => {
if (results.items.length >0) {
return results.items[0].votesSum;
} else {
return 0; // no records were found so return 0
}
})
.catch ((error) => {
console.log("[GetAllSumVotes()]::Error trying to read from Competition collection. Error was: "+error.message);
return 0;
})
}
// the function where this is put in must also have async added to the front of it
// since we're using the await
let sumVotes = await GetAllSumVotes()
console.log("SumAllVotes:",sumVotes);