Querying and displaying user-specific pieces in a clothing brand project.

7 replies
Last updated: Mar 23, 2022
Hey everyone! I have a project I'm working on for a clothing brand where users are able to add what they own to their "closet". I added a button to the product page that when clicked adds the PieceID to an array and stores the items in the users closet. The problem I'm facing is that when the user goes to their closet page I'd like to query/show the pieces they have based on what's in their array. Here's the code snippet I use to query for the pieces:
sanityClient.
          fetch(`*[_type == "piece"]{
              title,
              slug,
              pieceID,
              mainImage {
                  asset->{
                      _id,
                      url
                  },
                  alt
              },
          }`)
          .then((data) => setPieceData(data))
          .catch(console.error);

Mar 22, 2022, 11:30 PM
Hey! So the users are stored in MongoDB. In the database they have an array called pieces and whenever the button on the product page on the front end is clicked it adds the pieceID to the array pieces
Mar 23, 2022, 6:34 PM
Are the pieces in any way referencing a user, though? Or is it only in this array in MongoDB that it exists?
Mar 23, 2022, 6:56 PM
Yeah so the pieces themselves don't reference a user, but the user has a collection of pieces stored in MongoDB. Once the user visits their profile/closet I'd like to send a query to sanity for only the pieceIDs that are in the users array. Sorry if I'm confusing you ๐Ÿ˜…
Mar 23, 2022, 7:13 PM
No worries, just trying to figure out the approach here! Since Sanity isn't aware of which pieces belong to which users, you'll have to query MDB for the array of pieces for the user, then pass them in as params to your GROQ query. For example:
const query = `*[_type == "piece" && pieceId in $userPieces]{
              title,
              slug,
              pieceID,
              mainImage {
                  asset->{
                      _id,
                      url
                  },
                  alt
              },
          }`
const params = {
  userPieces: //insert your MDB array here
}

sanityClient.
          fetch(query, params)
          .then(setPieceData)
          .catch(console.error);
Mar 23, 2022, 8:35 PM
user M
THANK YOU! Ugh I love this community
Mar 23, 2022, 9:38 PM
Worked flawlessly
Mar 23, 2022, 9:38 PM
Glad to hear it!
Mar 23, 2022, 9:40 PM

Sanityโ€“ build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?