Code example: get product collection for a Wix Stores product

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. :slight_smile: 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
})
})

2 Likes

wow! thank you very much

Thanks!! I was just struggling to get a collection, since the box with sizes had to be different for women’s and men’s clothing. I really spent a week looking for different options. And thanks to you, everything worked for me!

I’m so glad to hear that, Elena! I thought others might be looking for the same solution. Wishing you much success with your shop, Michiel

Wowwwwww! Thank you, I have been needing this for months!