How to do computations from the data in the collection?

I need to compute the data in the collection and show the output in the site page.

Hi, This can be done easily.

Use ’ wixData ’ functions (get or query) to retrieve the record from the collection, then use some simple code to compute and show it.
Lets say I have a collection that hold information regarding people and the number of their cars, and I want to sum up all of it, and show it in a text component called ‘#text1’. Here’s how I would do it:

wixData.query("myCollection").find().then( (results) => { 
        const items = results.items;  
        let totalNumberOfCars = 0;
        items.forEach(person => {
                totalNumberOfCars += person.carsCount;
        });
        $w('#text1').text = `Total: ${totalNumberOfCars} Cars!`
    } ) .catch( (err) => { let errorMsg = err; } );

Hope this helps,

Liran.

Hi, could you please assist me with this?

I have a date and I need to add 25 working days to that date.

I have a dataset called Holidays - which is two columns name of holiday (holiday) and date of holiday (holidayDate). Another dataset called Feeback, where the date of sale and the delivery dates are held.

So if my date is the date of sale (orderConfirmation) and I need to add 25 working days as the delivery date (deliveryDate) - how would I do that?

Thank you

Hi Liran,

I’m trying the above code, but my text is showing up as NaN - I’m missing something somewhere. Here’s what I have:

wixData.query(“GroupOne”)
.find()
.then((results) => {
const items = results.items;
let totalGroupOnePoints = 0;
console.log(items);
items.forEach(_id => {
totalGroupOnePoints += _id.numberOfPoints;
});
$w(‘#text35’).text = ‘Total: ${totalGroupOnePoints} Points!’; //Currently returns NaN
console.log(totalGroupOnePoints + ’ 2ndlog’); //Currently returns NaN 2ndlog
}).catch((err) => {
let errorMsg = err;
});

My database is named GroupOne, I’m pretty sure that part is fine.
I’m aiming to total the column ‘numberOfPoints’ in this table.
My console.log(items) successfully returns a large array with all items in the table.

I understand that for each line in the db I need to add that number to my totalGroupOnePoints variable.

Thanks in advance,
Liam

Don’t worry, as usual sloppy column naming has come back to bite me!

For anyone who visits this in the future, the above code works fine, I’d simply labelled by column as numberOfPoints when it should have been numberofPoints.

For any future troubleshooting:

  • Neither mine nor Liran’s code includes the line:
    import wixData from ‘wix-data’;
    Don’t forget to include that first!
  • The things in my code that you’ll need to change to suit your own database structure are:
    GroupOne = Database name
    totalGroupOnePoints = your constant name, this is arbitrary but name it something descriptive
    _id = the identifier column from your database
    numberofPoints = the name of the column you’re wanting to sum
    #text35 = the id of the element on the page you’re wanting to display the value on

Happy coding!

im still having issus woth this

is this right
import wixData from ‘wix-data’;

wixData.query(“Tattooinfo”) //my database
.find()
.then((results) => {
const items = results.items;
let totalernings = 0;
console.log(items);
items.forEach(_id=> { //dont know about this

		totalernings += _id.artisttake; //artisttake = column 
	}); 


	$w('#input2').value = 'Total: ${totalernings} Points!'; //Currently returns NaN 
	console.log(totalernings + ' 2ndlog'); //Currently returns NaN  2ndlog 
}).catch((err) => { 
	let errorMsg = err; 
}); 

Hi Cameron,

Sounds like you’re on the right track.
To approach this broadly, it looks like you’re trying to sum the totals in the column named artist take (with the column Field Key artisttake). Is that correct?

As far as I can see, this should accomplish that. What this code does is it runs through each of the items in the database that matches your search conditions (using forEach), and adding the artisttake to your totalernings variable, which begins at 0.

It looks like some of those values in the database are blank, I wonder if that could be relevant? 0 + undefined returns an error, so this seems likely.

Things to try:

  • Change blank artisttake values in the database to 0 (you’ll need to do some data validation via hooks in the future to clean this data). Try again now.
  • Check that all your variables and Field Keys are correct (check them in your code vs the database).

Don’t forget to use the Read-Search-Ask approach when you run into issues!
https://forum.freecodecamp.org/t/the-read-search-ask-methodology-for-getting-unstuck/137307

Good luck!

thanks man
ive reset the data so there are no blank info
still reading nan

import wixData from ‘wix-data’;

wixData.query(“Tattooinfo”)
.find()
.then((results) => {
const items = results.items;
var totalernings = 0;
console.log(items);
items.forEach(artisttake => {
totalernings += artisttake.Artistcut;
});
$w(‘#input2’).value = ‘$’ + totalernings; //Currently returns NaN
console.log(totalernings + ’ 2ndlog’); //Currently returns NaN 2ndlog
}).catch((err) => {
let errorMsg = err;
});

items.forEach(artisttake => { this is the feild key???

what should (in your code) _id be?
is that the coloumn

also this is what i get in console

Hi Cameron

It looks like you’re just about there. Your screenshot shows that your line
console.log(items);
is successfully logging all items in the collection, so we know that the code up until that point is good.
“_id” is Wix’s unique identifier for each row in the database. You’re fine to use “_id” in this spot as well. You can see in your console.log(items); it’s printing the _id of each item in the db (as well as all of the other columns for each item).

That section of the code is basically saying that for each of the _id’s in the result set, add the artisttake to our variable that we defined just before that.

Is your artisttake column in the database set to data type number? If it’s set to string this could throw an error.

After typing that, I think I found the error in your code. Here it is corrected. I’ve also corrected the spelling of your totalEarnings variable and taken the liberty of matching it with variable capitalisation convention :wink:

wixData.query(“Tattooinfo”)
.find()
.then((results) => {
const items = results.items;
var totalEarnings = 0;
console.log(items);
items.forEach(_ id => {
totalEarnings += _id.artisttake;
});
$w(’ #input2 ‘).value = ‘$’ + totalEarnings; //Currently returns NaN
console.log(totalEarnings + ’ 2ndlog’); //Currently returns NaN 2ndlog
}).catch((err) => {
let errorMsg = err;
});

Hey
just tried your code still getting the same out come is mine
looks like its working but still coming up with “nan”
yeah the colloumn in set to numbers

i lie
its did work
there was a black spot in the database
can i wipe clean the data base
i tred to “crtl-a” the delete but just made them black?

also can i add filters. eg on eazys data?

is there a way i can pull data from data sets?
so i show each artist how to download there own, with filters so the can have a copy of there earnings

by the way
thanks heap liam
been a big heap

Hi Cameron,
Great! Glad that part is working well.
Don’t forget to use Read-Search-Ask when you have issues!

I did a quick google and found this link here:

Hi geovel,
You can delete two ways…

  1. In the editor, you can select more than one row at a time of a collection, and then right click/delete.
  2. Or, set up a temporary page, add a dataset and connect it to your collection. Add the following code to the onReady() function of the page:$w(“#dataset1”).onReady(async() => { if ($w(“#dataset1”).getCurrentItem()) { await $w(“#dataset1”).remove(); while ($w(“#dataset1”).hasNext()) { await $w(“#dataset1”).next(); await $w(“#dataset1”).remove(); } } });Run preview and you delete the contents of the sandbox collection. Run the live site and you delete the contents of the live collection.
    Just be careful you don’t trash something important.
    Have fun,
    Yisrael

Filters are built into Wix’s wixdata.query functions.

Here’s an example edit to part of your code:

wixData.query(“Tattooinfo”)
.eq(“daycost”, “50”)
.find()
.then((results) => {…

You can use the wixData.query function to pull data from your database too, the code you enter after “.then((results =>…” will determine what you do with the database results - eg if you want to use them to display some results etc.

Best of luck!