Hi everyone 
I’ve been trying to access a reference field by code, I think that the method I use used to work, but now I get “undefined”.
Here’s the code:
$w('#articlesDataset').getItems(0, 7).then( (result) => {
let items = result.items;
let totalCount = result.totalCount;
for (let i = 0; i < totalCount; i++) {
let label = items[i].title;
let tKey = `${language}_Title`;
let translatedLabel = items[i].translate.tKey;
console.log(items[i], translatedLabel)
}
})
“translate” is the ID of the reference field in the main database.
${language}_Title
is the field ID in the second collection that has a reference field to represent it in the first collection, for example: “he_Title”, “de_Title” and so on.
Perhaps I’m using the wrong way, so what’s the right way to do it?
I appreciate any help guys.
Thanks.
Ahmad
I recommend you to use wix-data query() along with include() in order to query all of the items including the referenced ones.
If you want to get only the referenced items, then you should use queryReferenced()
Hi @anhelinak , thank you for your suggestion.
Why do I have to query the collection? The items are already there from the dataset, so it should be just a matter of accessing the reference field.
As a way around to avoid making major changes to the actual code, I used the dataset to get the ID ( _id ) or the referenced field and then query it and return the data, it’s just a few more lines (8-12) for each, but it’s a lot of lines to add for each dataset, this method should be built-into the dataset API.
function getReferencedItem(id, referencedCollection) {
return wixData.query(referencedCollection).eq('_id', id).find().then((result) => {
if (result.items.length > 0) {
let item = result.items[0];
return item;
} else {
return {'type': 'Error', 'message': "Couldn't retrieve the Item"}
}
}).catch((err) => {
return {'type': 'Error', 'message': "Couldn't retrieve the Item"}
})
}
That’s the easiest way I came out with, in order to achieve the same result without changing a lot of the code structure.
What do you think? And is there any simpler ways?
Thanks.
Ahmad