Conversations about creating, managing, and using metafields to store and retrieve custom data for apps and themes.
Hi
I have a script to import products and add MetaField on product with "REMOTE_PRODUCT_ID" for connect Shopify product with my remote product, this work.
But when i want check if product exist have this.
const { admin, session } = await shopify.authenticate.admin(request);
const exist_product = await admin.rest.resources.Metafield.all({
session: session,
limit: 1,
metafield: {namespace: "MY_NAME_SPACE", owner_resource: "product", key: "RELATIONAL_PRODUCT_ID"}
});
The metafield stored with namespace and this show success on product.
The const exist_product is a MetaField from "test_data" namespace
Exist product [
Metafield {
id: xxxxxxxxxx,
namespace: 'test_data',
key: 'alpine_sports',
value: '["snowboarding"]',
description: null,
owner_id: xxxxx,
created_at: '2024-04-03T07:05:40-04:00',
updated_at: '2024-04-03T07:05:40-04:00',
owner_resource: 'shop',
type: 'list.single_line_text_field',
admin_graphql_api_id: 'gid://shopify/Metafield/xxxxxxxxxxx'
}
]
If change my code to
const { admin, session } = await shopify.authenticate.admin(request);
const exist_product = await admin.rest.resources.Metafield.all({
session: session,
limit: 1,
namespace: "MY_NAME_SPACE",
metafield: { owner_resource: "product", key: "RELATIONAL_PRODUCT_ID"}
});
This response is empty, but i can see MetaField on my product.
Resume: I want check if product exist by MetaField (key and value). What am I doing wrong?
Thanks!
@DanielRiera Not sure if this is doable at the moment with the rest api. One thing you can do is use GraphQL api to query products and iterate over the product array to check for the metafield value.
For example:
const { admin } = await authenticate.admin(request);
const response = await admin.graphql(
`#graphql
query {
products(first: 250) {
edges {
node {
id
title
handle
metafield(namespace: "METAFIELD_NAME_SPACE", key: "METAFIELD_KEY") {
key
namespace
value
}
}
}
}
}`,
);
const data = await response.json();
const productsWithMetafieldValue = data?.products?.edges?.filter((product) => product?.node?.metafield?.value === "YOUR_METAFIELD_VALUE")
Hello! Thanks for your answer,
Yes, but a store can have thousands of products, this is not a solution since I have to go through all the products to find the product I need, it is not effective for development, I do not understand why there cannot be a filter as simple as "I need products that have this key goal."
In the end what I have done is to store the Shopify product ID related to the store and the supplier's product ID in the supplier, it is a waste of time since now I have to implement actions when the user deletes the Shopify product, so, more points of error.
Thank you so much! I appreciate your response.