👋 Next.js Conf 2024: Come build, party, run, and connect with us! See all events

Groq query for retrieving document ID based on product ID

8 replies
Last updated: Aug 18, 2020
What would possibly be a groq query for this
"result":[1 item
0:{10 items
"_createdAt":"2020-08-17T23:14:12Z"
"_id":"Gk1LBo8Kg5xEVuqFLjoonz"
"_rev":"Gk1LBo8Kg5xEVuqFLjoojw"
"_type":"products"
"_updatedAt":"2020-08-17T23:14:12Z"
"image":{2 items
"_type":"image"
"asset":{...}2 items
}
"name":"Testing Product"
"price":"5000"
"price_id":"price_1HHHWnHk5l44uIELkHjFxVc2"
"product_id":"prod_HqzVaPGvVvUR5s"
}
]
Where I get the document id as a result
Aug 17, 2020, 11:58 PM
Assuming you’re having your key on
product_id

a groq query could look like this:

*[_type == "products" && product_id == "prod_HqzVaPGvVvUR5s]{
    _id
}

Aug 18, 2020, 12:23 AM
Assuming you’re having your key on
product_id

a groq query could look like this:

*[_type == "products" && product_id == "prod_HqzVaPGvVvUR5s]{
    _id
}

Aug 18, 2020, 12:23 AM
I do have the product id I tried something like this
      const query = `*[_type == "products" && product_id == ${payload.data.object.product}]`;
consoling the payload does give me the prodict_id now this is my fetch

 client.fetch(query).then((products) => {
        console.log("products");
        console.log(products);
        console.log("products");
      });
Does this work is params needed?
Aug 18, 2020, 12:54 AM
I just get a empty array in the fetch
Aug 18, 2020, 1:00 AM
when I console my query it looks like this
*[_type == "products" && product_id == prod_HqzVaPGvVvUR5s]
Aug 18, 2020, 1:09 AM
your product ID should probably be wrapped in quotes, though i’m not sure that’ll solve the issue
Aug 18, 2020, 1:10 AM
(also as an aside, I highly recommend installing the Vision plugin for testing your GROQ queries: https://www.sanity.io/docs/the-vision-plugin you can use it to test the explicity query you just logged and make sure that’s functioning as you expect it to)
Aug 18, 2020, 1:12 AM
Got it, it needed the quotes. Thanks!
Aug 18, 2020, 1:16 AM

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?