shopifyshopify-apishopify-api-node

How to update product metafield value by using Graphql?


I'm trying to update product metafield value but I'm not sure why this doesn't work. const

 const session = await Shopify.Utils.loadCurrentSession(
      req,
      res,
      app.get("use-online-tokens")
    );
    const client = new Shopify.Clients.Graphql(session.shop, session.accessToken);
    
    const data = await client.query({
      data: `{
        mutation{
          productUpdate(input:
            {
              id: "gid://shopify/Product/4532387151956",
              metafield:  {
                  namespace: "custom",
                  key: "limit",
                  value : "550",
                  valueType: "INTEGER"
                }
            }) 
            userErrors {
              field
              message
            }
          }
        }
      }`
    });

Please help me with this. Thanks.


Solution

  • I have ever ran into this problem. Because you don't have metafield id like "gid://Metafield/19201930". So you must get this metafield id. And you should type same code with the same code with your new metafield id. Try this.

    const data = await client.query({
      data: `mutation {
        productUpdate(input: {
          id: "yourid",
          metafields:[{
            namespace: "custom",
            key: "limit",
            value: "yourvalue"
          }]
        }) {
          product {
            metafield(namespace:"custom", key:"limit") {
              id,
              namespace,
              key,
              value
            },
            id
          }
        }
      }`,
    });
    
    await client.query({
      data: `mutation {
        productUpdate(input: {
          id: "your product id",
          metafields:[{
            namespace: "custom",
            key:"limit",
            value:"your value",
            id: "${data.body.data.productUpdate.product.metafield.id}", 
          }]
        }) {
          product {
            metafield(namespace:"custom", key:"limit") {
              namespace
              key
              value
              type
              id
            }
          }
        }
      }`,
    });