GROQ Query Error - Error: `String Literal Expected`
I can see the issue with your query! The problem is that count() in GROQ doesn't work the way you're trying to use it. You're attempting to query inside count(), but count() is designed to count elements in an array or count documents in a separate query context.
The correct approach is to use count() with a separate query that uses the references() function. Here's the fixed query:
*[_type == "seller"] {
_id,
name,
sellerImageUrl,
sellerRating,
"serviceCount": count(*[_type == "service" && references(^._id)])
}The key changes:
- Use
references(^._id)instead of trying to access_refdirectly. Thereferences()function checks if any reference field in the service document points to the current seller's_id. - Start the count query with
*to indicate you're querying all documents of type "service" - Use the parent operator
^to reference the current seller document from the outer query
The references() function is specifically designed for this use case - it checks all reference fields in a document to see if they point to a specific ID. This is much cleaner than trying to access _ref directly, which would require you to know the exact field name.
As shown in the GROQ count documentation, this pattern of using count(*[... && references(^._id)]) is the standard way to count reverse references in GROQ.
If for some reason your services reference sellers through a specific field (let's say seller), you could also write it more explicitly:
*[_type == "seller"] {
_id,
name,
sellerImageUrl,
sellerRating,
"serviceCount": count(*[_type == "service" && seller._ref == ^._id])
}But the references() approach is generally preferred since it works regardless of the field name!
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.