Wix Query in Repeater For Loop Not Returning Items...

Webpage: cosworthvega.com/reconcile-registry-histories
Dataset1: CVOA-Registry-History containing dash_no, entry_date, and content.
Dataset2: CVOA-Registry containing dash, vin, email of the owner, other info not needed here

There may be from to to many history records for a given dash number. The purpose is to show history records that have been entered for a given dash but not “parent” entry exists.

Code has been provided by Steve in another forum post to get the unique history records. However, their is an error in displaying the entry date on the repeater, AND the added code to retrieve the car’s vin and email address for the car owner is not working but giving errors.

Here is a screen shot of the webpage definition. If and email address is not found then the page field text "*** Not In CVOA Registory **** is not replaced.


------- CODE --------

// For full API documentation, including code examples, visit Velo API Reference - Wix.com
import wixData from ‘wix-data’;

let DashNo;
let VIN;
let EntryDate;
let RegisteredTo;

$w.onReady(() => {
// We return this which will delay page rendering until the data is ready
return wixData.query(“CV-History-Registry”)
.ascending(‘dash_no’) // Sort: by car’s unique dash number
.descending(“date”) // Sort: Date column is populated by a date field from the data collection
.find()
.then((result) => {
let filteredRegistry = ; // Initialize the results list we need
let uniqueColumnValue = “”; // Used to filter out the secondary dash_no records

// Loop through the result list and remove unwanted records
for ( let i = 0 ; i < result.items.length ; i++) {
let itemUnderTest = result.items[i]; // Check to see if we have see the dash_no before
if (uniqueColumnValue === itemUnderTest.dash_no) {
// We have seen a record with this dash_no before so skip this one
continue ;
}
// If we get here we have a unique (possibly the first of a list) item record
filteredRegistry.push(itemUnderTest); // Remember the dash_no
uniqueColumnValue = itemUnderTest.dash_no;

    } 

// The registry is now filtered
// Give the filtered list to the repeater to work with
$w(‘#repeater1’).data = filteredRegistry;

// Now Update the repeater view
$w(‘#repeater1’).forEachItem(($item, itemData, index) => {

// Get the VIN# and Owner Email from the CVOA-Registry dataset…
DashNo = itemData.dash_no;
console.log("Getting VIN and Owner for Dash: " + DashNo)

        wixData.query("CVOA-Registry") 
          .limit(1) 
          .eq("dash", DashNo) 
          .find() 
          .then( (results) => { 
          let  firstItem = results.items[0]; 
          VIN = firstItem.vin; 
          RegisteredTo = firstItem.email; 
        } ) 
        . catch ( (err) => { 
         let  errorMsg = err; 
          console.log('ERROR: ' + errorMsg) 
        } ); 

// Load the repeater element values
$item(‘#dash’).text = itemData.dash_no;
$item(‘#vin’).text = VIN;
$item(‘#owner’).text = RegisteredTo;
$item(‘#date’).text = itemData.entry_date; // GETTING ERROR:
});
});
});
----- END CODE ----

  1. Date Display Error:
    “Wix Code SDK Error: The text parameter that is passed to the text method cannot be value Wed Dec 3 2014 00:00:00 0500-GMT (Eastern Standard Time), It must be of type string.”

In my original code that was not filtering out the duplicates I had the following code snippet that did display the date as I wanted, but I could not figure out where to place this code in the rewrite…
let repeatedElement = $w(" #date ");
let D_String = new Date(itemData.entry_date)
let D_Locale = D_String.toLocaleDateString(“en-US”)
repeatedElement.text = D_Locale

  1. The wix query within the for loop Errors:
    “Wix Code SDK Error: The text parameter of ‘vin’ that is passed to the text method cannot be null or undefined”.

“Wix Code SDK Error: The text parameter of ‘owner’ that is passed to the text method cannot be null or undefined”.

  1. Also, there are approximately 3500 unique history records to be displayed. With my dataset definition set to 100, will the pagination widget at the bottom of the page still work? Right now it is not, possibly because of these errors?
  1. I don’t see any of the code from your post on the list-registry-history-urls page.

  2. In some cases vin might be null as some records in the CVOA-Registry collection vin is empty (therefore, null ).

  3. It should work, but the rest of the stuff has to be fixed.

OOPS… wrong page: reconcile-registry-histories

Here’s the little chunk of code with the date formatting:

// Load the repeater element values
$item('#dash').text = itemData.dash_no;
$item('#vin').text = VIN;
$item('#owner').text = RegisteredTo;
let D_String = new Date(itemData.entry_date)
let D_Locale = D_String.toLocaleDateString("en-US")
$item('#date').text = D_Locale;

BTW - Remember that a database query is asynchronous, so the above chunk of code should be in the .then() of the query:

wixData.query("CVOA-Registry")
  .limit(1)
  .eq("dash", DashNo)
  .find()
  .then((results) => {
 let firstItem = results.items[0];
 VIN = firstItem.vin;
 RegisteredTo = firstItem.email;

 // Load the repeater element values
 $item('#dash').text = itemData.dash_no;
 $item('#vin').text = VIN;
 $item('#owner').text = RegisteredTo;
 let D_String = new Date(itemData.entry_date)
 let D_Locale = D_String.toLocaleDateString("en-US")
 $item('#date').text = D_Locale; //itemData.entry_date; // GETTING ERROR:  
 //  }); 
  })
  .catch((err) => {
 let errorMsg = err;
 console.log('ERROR: ' + errorMsg)
  });

There is still an issue of many fields in the collection being empty and therefore returning nulls.

Looks like I have it working as desired, EXCEPT… pagination widget at bottom of page doesnt work. Is that because I am populating the repeater manually? Do I need to save the index? How do I make this work?
Thanks Much!

Also, I put in console.log("Rec# " +i ); the for loop is only getting 46 unique entries. How/where do I define the array length?

OK. I added .limit(100) to the first query. Now I am getting a page of entries, but I still cannot figure out how to get next page of entries. Just for grins I set the limit to 1000… it ran, and ran and ran and returned a lot of entries… some of which were populated OK while others were not. That is NOT the solution. I need to be able to page thru the database, 100 at at time. There are approximately 3500 unique entries.

Because you’re setting the Repeater manually, you’ll need to handle the pagination manually. Let’s play with your pagination component…

:beer:To start with, disconnect the Pagination component from the dataset.
:beer: Then, add an onClick() event handler. For now, try this:

export function pagination1_click(event) {
    console.log(event.target.currentPage);
}

:beer: Run the page in Preview.
:beer: Click on the > and < arrows in the pagination component.
:beer: In the console you’ll see the current page number.

Now all you’ve got to do is to handle the rest of the logic for the page queries.

Ya know something, I’m gonna want to get a Vega. :beers:

Thanks, I figured as much. OK I disconnected an console log shows pageno. I assume that in the pagination event I use getCurrentPageIndex . Then in main query Load page?

Hello , cwvega76 !

You have defined the task like this:

Dataset1: CVOA-Registry-History containing dash_no, entry_date, and content.
Dataset2: CVOA-Registry containing dash, vin, email of the owner, other info not needed here.
There may be from to to many history records for a given dash number. The purpose is to show history records that have been entered for a given dash but not “parent” entry exists.

Your task can be solved with the help of repeaters in the form of tables.This will allow sorting and filtering for database analysis.

I wrote an example of a possible implementation of a search for records in “CVOA-History” not registered in “CVOA-Registry”.
Example :
#dataset2: CVOA-Registry containing dash, vin, email of the owner, other info not needed here. The example contains 5 items with dash “0001”, “0002”, “0003”, “0004”, “0005”,
#dataset3: CVOA-Registry-History containing dash_no, entry_date, andother info not needed here. The example contains 21 items with dash_no “0001”,…, “0008” ( some items are duplicated)
The purpose is to show history records that have been entered in “CVOA-Histiry”, but not exists in "CVOA-Registy " for field “dash”.

To mark the fact of registration “dash” in the “CVOA-Registy” was introduced an additional special field “regCVOA” in database “CVOA-Histiry” , by which filtering is possible.

The contents of the databases can be viewed in tables 1 and 2

Using the buttons, tables can be sorted and filtered by the values of the selected row.
Procedure for search history records that have been entered in “CVOA-Histiry” but not exists in “CVOA-Registy” is launched using the special button .

First, all the “dash” from the “CVOA-Registy” (#dataset2) are recorded in the Reg array (Steve also used such an array).
Second, each item of the “CVOA-History” (#dataset3) is checked for compliance and the results are recorded in the “regCVOA” field.
Thirdly, #dataset3 is filtered.

For the demonstration, I provided a special button to clear the registration field. After the second search procedure, the value of the field should be restored.
This is how this small database manager looks in the editor.
Below is the code.

Try how it works https://211026a.wixsite.com/mysite-2 .

//http://wix.to/94BuAAs
import wixData from 'wix-data';
$w.onReady(function () {
    $w('#table2').show();
    $w('#text16').hide()
    $w("#text14").text = " " + $w("#dataset2").getTotalCount();
    $w("#text15").text = " " + $w("#dataset3").getTotalCount();
});

function asortcol(sdataset, scol) { //Sort sdataset ascending
    $w(sdataset).setFilter(wixData.filter());
    $w(sdataset).setSort(wixData.sort()
        .ascending(scol))
}

function dsortcol(sdataset, scol) { //Sort sdataset descending
    $w(sdataset).setFilter(wixData.filter());
    $w(sdataset).setSort(wixData.sort()
        .descending(scol))
}

function filtrtcol(sdataset, fcol, ffild) { //filter sdataset 
    $w(sdataset).setFilter(wixData.filter()
        .eq(fcol, ffild))
}

function count() { // vew of TotalCounts
    $w("#text14").text = " " + $w("#dataset2").getTotalCount();
    $w("#text15").text = " " + $w("#dataset3").getTotalCount();
}
var ddas, dvin, down, dreg, dend, drey, dren
var c2, c3 // for TotalCounts
var Reg = []; // Initialize the results list dash from #dataset2 we need
function regcvoa() { //field "regCvoa" registration function
    ddas = $w("#dataset3").getCurrentItem().dash_no
    dren = "*** Not In CVOA Registory ***"; // here you can specify the desired texts
    drey = "Yes";
 var regy = Reg.indexOf(ddas) < 0 ? dren : drey ////Search for non-existing in Reg[]
    $w("#dataset3").setFieldValue("regCvoa", regy)
}
export function table1_click(event) { //select the item and filter "#dataset3" on "dash" "#dataset2"
    ddas = $w("#dataset2").getCurrentItem().dash;
    dvin = $w("#dataset2").getCurrentItem().vin;
    down = $w("#dataset2").getCurrentItem().owner;
    filtrtcol("#dataset3", "dash_no", ddas);
    count();
}
export function table2_click(event) { //select the item "#dataset3"
    ddas = $w("#dataset3").getCurrentItem().dash_no;
    dreg = $w("#dataset3").getCurrentItem().regCvoa;
    dend = $w("#dataset3").getCurrentItem().entry_date;
    count();
}
export function button1_click(event) { // filter cleaning "#dataset3"
    $w("#dataset3").setFilter(wixData.filter());
    count();
}
export function button2_click(event) { //Search for non-existing CV-Registry
    $w('#table2').hide();
    $w('#text16').show();
    $w("#dataset2").setFilter(wixData.filter())
    asortcol("#dataset2", "dash");
    c2 = $w("#dataset2").getTotalCount();
    $w("#dataset2").setCurrentItemIndex(0)
        .then(() => {
            ddas = $w("#dataset2").getCurrentItem().dash;
            Reg.push(ddas)
 for (let i = 0; i < c2; i++) {
                $w("#dataset2").next()
                    .then((item) => {
                        ddas = $w("#dataset2").getCurrentItem().dash;
                        Reg.push(ddas)
                    })
                    .catch((err) => {
 let errMsg = err;
                    });
            } //Reg [] complete
 // Cycle  for "#dataset3" - search for non-existing CV-Registry
            $w("#dataset3").setFilter(wixData.filter())
                .then(() => {
                    c3 = $w("#dataset3").getTotalCount();
                    regcvoa(); // register the first element
 for (let j = 1; j < c3; j++) {
                        $w("#dataset3").next()
                            .then(() => {
                                regcvoa();
                            })
                            .catch((err) => {
 let errMsg = err;
                            });
                    }
                });
 //
            $w("#dataset3").save()
                .then(() => {
                    $w("#dataset3").setFilter(wixData.filter()
                            .eq("regCvoa", dren)) //filter for non-existing CV-Registry
                        .then(() => {
                            $w('#text16').hide();
                            $w('#table2').show();
 //count();
                        })

                })
        })
}
// button`s reactions
export function button3_click(event) { asortcol("#dataset2", "dash") }
export function button4_click(event) { asortcol("#dataset2", "vin") }
export function button5_click(event) { asortcol("#dataset2", "owner") }
export function button6_click(event) { dsortcol("#dataset2", "dash") }
export function button7_click(event) { dsortcol("#dataset2", "vin") }
export function button8_click(event) { dsortcol("#dataset2", "owner") }
export function button9_click(event) { filtrtcol("#dataset2", "dash", ddas) }
export function button10_click(event) { filtrtcol("#dataset2", "vin", dvin) }
export function button11_click(event) { filtrtcol("#dataset2", "owner", down) }
export function button12_click(event) { filtrtcol("#dataset3", "dash_no", ddas) }
export function button13_click(event) { filtrtcol("#dataset3", "regCvoa", dreg) }
export function button14_click(event) {
    $w("#dataset3").setFieldValue("regCvoa", "**"); //clean field
    $w("#dataset3").save();
}

To check the work with large databases, can you publish your 2 CSV files on the file hosting service?

1 Like

Thanks, coming from an Oracle database I was looking for what would be done with SQL in “select distinct”… I found out from Wix developers that this has not been implemented but is planned for a future date. I just exported the two databases into Excel and did my reconciliation with that.

I really really do appreciate your efforts! This is a great example, but for now I have solved the probelm.
Regards,
JD

1 Like