Trying To Retrieve ONLY the First Item in a Dataset

I have a dataset that contains multiple historical records (entry_date) for a given item(dash_no). I am trying to retrieve JUST the first entry_date for a given dash_no using the firstItem(0) index.

It is not working… the console log shows the 50th record as that is the number of records set to retrieve in the dataset settings. The repeater shows all items for all dash_no’s?

import wixData from ‘wix-data’;

$w.onReady( function () {
$w(“#dataset1”).onReady( () => {

wixData.query(“CV-History-Registry”)
.limit(1)
.gt(“dash_no”, “0000”)
.find()
.then( (results) => {
let firstItem = results.items[0];
console.log("Getting 1st History item for Dash#: " + firstItem.dash_no );
})

$w(“#repeater1”).onItemReady( ($w) => {
const originalDate = $w(“#date”).text;
const newDate = originalDate.split(’ ‘).splice(0, 4).join(’ ‘);
$w(’#edate’).text = newDate;
$w(‘#date’).text = newDate;
$w(“#origDate”).hide();
});
});
});

46 LIkes But NO Solution???

Look closely… do NOT want subsequent records for same dash#. Purpost of this report is to identify any


CV-History records for which there is NO parent entry in the CV-Registry.

Hi!
Look there

If a property contains a number as a String, that value will be compared alphabetically and not numerically. Items that do not have a value for the specified property are ranked lowest.

  • String: Compares lexicographically, so “text” is greater than “Text”.

You set as String:

 .gt("dash_no", "0000") 

Maybe this is the problem?

I think this is a little more complex.

I am going to guess that the table fields are connected in the editor to the dataset $w(" #dataset1 ").

None of the code shown will do anything to change what is displayed in the table.
This snippet:

wixData.query("CV-History-Registry")
   .limit(1)
   .gt("dash_no", "0000")
   .find()
   .then( (results) => {
        let firstItem = results.items[0];
        console.log("Getting 1st History item for Dash#: " + firstItem.dash_no );
   })

Searches the data collection and only prints a console.log of the first item.

This snippet:

$w("#repeater1").onItemReady( ($w) => {
    const originalDate = $w("#date").text;
    const newDate = originalDate.split(' ').splice(0, 4).join(' ');
    $w('#edate').text = newDate;
    $w('#date').text = newDate;
    $w("#origDate").hide();
});

Loads a date value in each repeater Item.

The only way to do what you need is to disconnect the dataset bindings in the editor.
Load the data as your are doing in the query BUT don’t bother with a constraint, load everything. Then use a loop to process each record and remove records with identical dash_no values (except the first one).

Then assign the resulting array to $w(“##repeater1”).data and use $w(“#repeater1”).forEachItem() to display the repeater contents.

Steve

OK… I REWROTE the code …

// For full API documentation, including code examples, visit http://wix.to/94BuAAs
import wixData from ‘wix-data’;

$w.onReady( function () {

$w(“#dataset1”).onReady( () => {
let prevDash = “0000”
wixData.query(“CV-History-Registry”)
.gt(“dash_no”, prevDash)
.find()
.then( (results) => {
$w(“#repeater1”).forEachItem( ($w, itemData, index) => {
console.log(“Dash " + itemData.dash_no);
let repeatedElement = $w(”#date");
let D_String = new Date(itemData.entry_date)
let D_Locale = D_String.toLocaleDateString(“en-US”)
repeatedElement.text = D_Locale
prevDash = itemData.dash_no
console.log(“Showing 1st History item for Dash#: " + prevDash );
} )
.then(() => {
$w(”#repeater1").show();
})
})
})
})

============================
DOES THE SAME THING… continues to show all history records…

@cwvega76 Hi there.

OK as I mentioned above. If you have your dataset attached to the repeater and its elements then your code will not change anything.

To do what you want to do you need to you need to disconnect the bindings that you have between the dataset and the repeater and load the repeater in code.

The bindings I referred to are the Connect Repeater dialogue and also the ones that attach each element to the dataset:


If these are connected AND we want to used code to change the repeater values then you will get an unexpected result in the repeater. :slight_smile:

OK so let’s follow my directions above.

First let’s just load all of the CV Registry History.

NOTE: This code assumes that you have a manageable amount of data. If you have more than a thousand records in your VIN data collection then you will need to adapt the code to display content in pages.

We don’t need to filter the data (we can’t really filter the way you need to) so we will load it and then filter it once loaded.

wixData.query("CV-History-Registry")
.descending("date")  // Sort: assuming that the Date column is populated by a date field from the data collection
.limit(1000) // You have 
.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
    
});

OK now we should have removed the unwanted items so lets display the items in the repeater. The code below goes below the last comment in the find() request above.

// 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) => {
    // Load the repeater element values
    $item('#<dash number element ID>').text = itemData.dash_id;
    $item('#<vin number element ID>').text = itemData.vin_no;
    ... 
});

NOTE: You need to use the correct element name in the repeater for and the same for .

This can all be put in your onReady function like this:

$w.onReady(() => {
    // We return this which will delay page rendering until the data is ready
    return wixData.query("CV-History-Registry")
    .descending("date") // Sort: assuming that the 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) => {
            // Load the repeater element values
            $item('#<dash number element ID>').text = itemData.dash_id; 
            $item('#<vin number element ID>').text = itemData.vin_no;
            // Assign other elements  ...
        });
    });
});

Hope this helps
Steve

Thanks so much Steve. I just gave this a go. The repeater is now showing only the unique dash# as desired, but I have two problems.

  1. The entry_date is causing an error…"the text method cannot be set to the value Sat May 15, 2004… It must be of type string.

  2. The VIN# and OwnerEmail is NOT being picked up from the second dataset CVOA-Registry. The .catch is displaying error message:

Error: Type Error: Cannot read property of ‘vin’ of undefined

Again the purpose of this report is to identify any collection of CV-History-Registry records for which there is NO parent entry in the CVOA-Registry

New CODE:

// For full API documentation, including code examples, visit http://wix.to/94BuAAs
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’)
.descending(“date”) // Sort: assuming that the 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:
});
});
});

@cwvega76 Hi There.

Can you create a new post for this problem?
I think your initial question has been answered.
Trying To Retrieve ONLY the First Item in a Dataset

For the forum to be successful it helps that new problems are made easily accessible for other members to see and help out with. Check out Liran’s guidelines.

Also can you try to give as much information about what you are trying to do (as much as how you currently plan on doing it). The new information about “CVOA-Registry” was not disclosed in the first post so no one would be able to help.

You can refer to this post in any new one to maintain context.

Thanks!