OK I spent hours figuring this out, it is very tedious because you can’t get it from Datasets in the editor. Yes, I am talking about getting the product collection for a product in Wix Stores. Just sharing it here so you don’t have to solve the same puzzle
This code gets one collection name for each product, filtering out an unnecessary collection name (‘retail’ in this example).
Create a backend module called shop.jsw
import wixData from ‘wix-data’;
let options = {
“suppressAuth”: true ,
“suppressHooks”: true
};
export function getcollection(id) {
return wixData.queryReferenced(“Stores/Products”, id, “collections”)
.then((results) => {
if (results.items.length > 0) {
let collections = results.items.map(x => x.name)
let filteredcollections = collections.filter(item => item !== “Retail”)
return filteredcollections[0]
} else {
console.log(“no collection found”)
}
})
}
Frontend code: In this example, I get the product ID from the product page in Wix Stores. I get the collection name by calling the backend function above and I pass it on to an element on the page
import { getcollection } from ‘backend/shop’
$w.onReady( function () {
$w(‘#productPage1’).getProduct().then((results)=>{
let id = results._id
console.log(id)
return getcollection(id)
})
.then((result)=>{
console.log(result)
$w(‘#element’).text = result
})
})