Querying a reference field

I am trying to query a reference field to populate a repeater and I am having some difficulty. This is what I have found online so far but it’s not working.

function userDefinedFields () {
$w( ‘#dbApplications’ ).onReady(() => {
$w( ‘#rptApplications’ ).onItemReady( async ($w, itemData, index) => {
let description = itemData.jobRef;
const resDescription = await find_description_info
$w( ‘#txtDescription’ ).html = resDescription.substring( 0 , 150 ) + “. . .” ;
let closingDate = itemData.jobRef;
const resDate = await find_date_info
var options = {day: “numeric” , month: “long” , year: “numeric” };
var daysRemaining = Math.round( (itemData.closingDate - Date.now()) / 1000 / 60 / 60 / 24 )
$w( ‘#txtClosingDate’ ).text = resDate.toLocaleDateString( “en-GB” , options)+ " (" + daysRemaining + " days remaining) " ;
});
});
}

function find_description_info(event) {
return wixData.query( “Applications” )
.eq( “description” , jobRef)
.find()
.then((res) => {
return (res.items[ 0 ].description)
})
}

function find_date_info(event) {
return wixData.query( “Applications” )
.eq( “closingDate” , jobRef)
.find()
.then((res) => {
return (res.items[ 0 ].closingDate)
})
}

Hi, Erin :raised_hand_with_fingers_splayed:

You need to get the ID of the reference field first, then query the relevant collection with the ID you got from the reference field.

Reference fields holds the ID of the entry they’re representing as their value, so just simply get its value and query it.

Ahmad

So if my database was “Applications” and the reference field was “JobRef”, where in this code would I add the “JobRef” query? Sorry I am just learning code and it’s the first time I have had to query a reference field.

Hi, Erin

Assuming that the field is type of Date & Time and that its key is closingDate .
The same as your code, but the closing date value you need to get it with a query to the original database, and since the referenced field value is just the ID of the original entry in your Applications collection/database, we only need to query it and get the closing date value from the results.

Hope that helps

let closingDate = await wixData.query('Applications')
    .eq('_id', itemData.jobRef)
    .find()
    .then((result) => {
        if (result.items.length > 0) {
            return result.items[0].closingDate;
        } else {
            console.warn('No results were found')
        }
    })