Skip to content

Instantly share code, notes, and snippets.

@tonyspiro
Created June 9, 2020 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonyspiro/95dc64007db98ddaaf5bf8e54076e8e0 to your computer and use it in GitHub Desktop.
Save tonyspiro/95dc64007db98ddaaf5bf8e54076e8e0 to your computer and use it in GitHub Desktop.
Cosmic Advanced Queries
// To keep things concise, use the following bucket variable for the examples.
const bucket = Cosmic.bucket({
slug: 'bucket-slug',
read_key: "your-read-key-found-in-bucket-settings"
})
// Matches Objects with exact title
bucket.getObjects({
type: 'posts',
props: 'slug,title,content',
query: {
"title": "Post 1"
}
})
// Matches Objects greater than or equal to metadata value
bucket.getObjects({
type: 'posts',
props: 'slug,title,content',
query: {
"metadata.price": {
"$gte": 9.99
}
}
})
// Matches Objects with nested JSON metadata value (JSON Metafield)
bucket.getObjects({
type: 'posts',
props: 'slug,title,content',
query: {
"metadata.json_data": {
"is_awesome": true,
"other_data": {
"nested": "yep"
}
}
}
})
// Matches Objects with any metadata values
bucket.getObjects({
type: 'posts',
props: 'slug,title,content',
query: {
"$or": [
{
"metadata.grade": "A"
},
{
"metadata.grade": "B"
}
]
}
})
// Match Objects with string in content. Case insensive with $options.
bucket.getObjects({
type: 'posts',
props: 'slug,title,content',
query: {
"content": {
"$regex": "jamstack",
"$options": "i"
}
}
})
// Match Objects with any Multiple Object Metafield values
bucket.getObjects({
type: 'posts',
props: 'slug,title,content',
query: {
"metadata.categories": {
"$in": ["category_id-1","category_id-2"]
}
}
})
// Match Objects that don't have any Multiple Object Metafield values
bucket.getObjects({
type: 'posts',
props: 'slug,title,content',
query: {
"metadata.categories": {
"$nin": ["category_id-1","category_id-2"]
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment