How does one count occurrences in a collection in the database?
One of the columns in a collection in the database is numbers. I wish to count the occurrence of a specific number in the column. This is the code i the back end sow far:
import wixData from 'wix-data';
export function Counter(Number1) {
wixData.query("TestData")
.eq("PostalCode", Number1)
.count()
.then( (num) => {
let numberOfItems = num;
return numberOfItems;
} )
.catch( (error) => {
let errorMsg = error.message;
let code = error.code;
} );
}
In the above I would think the numberOfItems would contain the number of items. The front end looks like this:
In the console it displays undefined, which means that numberOfItems is undefined which is weird because the function returns numberOfItems. What’s wrong?
Is there a specific reason you are performing a count function on the backend without the need to suppress hooks or permission checks? You can do it on the frontend too.
However you can do it from the backend like this:
First, you need to make sure that the Database Field PostalCode is a Number field and not text.
Second put a return to the start of your query like this
The reason why I want to do it the in the back end is because I would like the change to add suppressions of hooks and other additions only accessibly in the backend.
However, it’s not counting… The backend code looks like this (as expected):
import wixData from 'wix-data';
export function Counter(Number1) {
return wixData.query("TestData")
.eq("PostalCode", Number1)
.count()
.then( (num) => {
let numberOfItems = num;
return numberOfItems;
} )
.catch( (error) => {
let errorMsg = error.message;
let code = error.code;
} );
}
My requirement is pretty simple, I have been trying to count the number of fields in a dataset collection and display the results in a textbook. No matter however I try with various iterations , the textbook displays 0.