Trying to get around performing Aggregation on a text field

Viewed 46

I am using Wix code/Javascript to try and sum items in a database collection - the only issue is whomever initially set it up created the nos field as text instead of an integer.

For some reason I can perform a max aggregation on the database which returns a 1, however I cannot sum it. (returns 0)

The way I see it is I have two options:

  1. Painstakingly create a new field with the correct data type for nos and copy the data over and change all inputs for the field (less than keen on this idea due to it being a live database)

  2. Use a function possibly $convert: to change the text value to an int to allow sum

My code is as below:

import wixData from 'wix-data';
import wixUsers from 'wix-users';

$w.onReady( function() {
   const filter = wixData.filter().eq("_owner", "SomeHashedValue");
   wixData.aggregate("CollectionName")
   .filter(filter)
   .group("_owner")
   .sum("nos", "sumnos")
   .run()
   .then( (results) => {
      console.log(results.items)
   } )
} )

Anyone know if option 2 is possible or if there's a better way of doing it? Note: I know I'm not using wix-users in the code but I will be, it's just easier for testing not to!

1 Answers

Not sure about Wix but in JavaScript you can easily convert a string to a number (int or float) by using the global methods:

var myString = "2";

var myNumber = Number(myString); // 2
var myInt = parseInt(myString); // 2
var myFloat = parseFloat(myString); // 2

Shorthand for converting a string to a number is to just add '+' before the string:

var anothernumber = +myString; // 2

MDN link for Number

Related