1 export const metadata = {
2 title: `${pageNumber} JSON Properties in Data Models`,
3 }
4
5 # {metadata.title}
6
7 In this chapter, you'll learn how to use and manage [JSON properties](../properties/page.mdx#json) in data models.
8
9 ## What is a JSON Property?
10
11 A JSON property in a data model stores any JSON-serializable value in a `jsonb` column.
12
13 For example, you can create a `Brand` data model with a `metadata` JSON property to store additional information about the brand:
14
15 ```ts highlights={[["6"]]}
16 import { model } from "@medusajs/framework/utils"
17
18 const Brand = model.define("brand", {
19 id: model.id().primaryKey(),
20 name: model.text(),
21 metadata: model.json(),
22 })
23 ```
24
25 By default, the TypeScript type of a `json` property is `Record<string, unknown>`. You can pass a type argument to use a different shape, including arrays:
26
27 <Note>
28
29 The type argument is supported since [Medusa v2.19.0](https://github.com/medusajs/medusa/releases/tag/v2.19.0).
30
31 </Note>
32
33 ```ts
34 import { model } from "@medusajs/framework/utils"
35
36 const Brand = model.define("brand", {
37 id: model.id().primaryKey(),
38 name: model.text(),
39 warnings: model.json<{ code: string; message: string }[]>(),
40 })
41 ```
42
43 <Note title="Tip">
44
45 To store an array of strings, use the [array property type](../properties/page.mdx#array) instead, which stores the value in a `text[]` column.
46
47 </Note>
48
49 ### Accepted Values in JSON Property
50
51 JSON properties support any JSON-serializable value, including objects, arrays, strings, numbers, and booleans. When the property stores an object, its keys are strings and values can be one of the following types:
52
53 - **Strings**: Text values.
54 - Empty strings remove the property from the JSON object. Learn more in the [Remove a Property from the JSON Property](#remove-a-property-from-the-json-property) section.
55 - **Numbers**: Numeric values.
56 - **Booleans**: `true` or `false` values.
57 - **Nested Objects**: Objects within objects.
58 - **Arrays**: Lists of values of any of the above types.
59
60 For example, a `metadata` JSON property can look like this:
61
62 ```json
63 {
64 "category": "electronics",
65 "views": 1500,
66 "is_featured": true,
67 "tags": ["new", "sale"],
68 "details": {
69 "warranty": "2 years",
70 "origin": "USA"
71 }
72 }
73 ```
74
75 ### What are JSON Properties Useful For?
76
77 JSON properties allow you to store flexible and dynamic data structures that can evolve over time without requiring changes to the database schema.
78
79 Most data models in Medusa's Commerce Modules have a `metadata` property that is a JSON object. `metadata` allows you to store custom information that is not part of the core data model.
80
81 Some examples of data to store in JSON properties:
82
83 - Custom gift message for line items in an order.
84 - Product's ID in a third-party system.
85 - Brand's category or tags.
86
87 ### What are JSON Properties Not Useful For?
88
89 JSON properties are not suitable for structured data that requires strict validation or relationships with other data models.
90
91 For example, if you want to re-use brands across different products, it's better to create a `Brand` data model and [define a link](../../module-links/page.mdx) to the `Product` data model instead of storing brand information in the product's `metadata` JSON property.
92
93 ---
94
95 ## How to Manage JSON Properties?
96
97 ### How Medusa Updates JSON Properties
98
99 Consider a Brand Module with a `Brand` data model as shown [in the previous section](#what-is-a-json-property). The [module's service](../../modules/page.mdx#2-create-service) will extend `MedusaService`, which generates methods like [updateBrands](!resources!/service-factory-reference/methods/update) to update a brand.
100
101 When you pass a JSON property in the `updateBrands` method, Medusa will merge the provided JSON object with the existing one in the database. So, only the properties you pass will be updated, and the rest will remain unchanged.
102
103 The following sections show examples of how to add, update, and remove properties in a JSON property.
104
105 <Note title="Prerequisite" forceMultiline>
106
107 The following examples assume you have a `brandModuleService` that is resolved from the [Medusa container](../../medusa-container/page.mdx). For example:
108
109 ```ts
110 const brandModuleService = container.resolve(BRAND_MODULE)
111 ```
112
113 </Note>
114
115 ### Add a Property to the JSON Property
116
117 Continuing with the Brand example, to add a `category` property to the `metadata` property, pass the new property in the `update` or `create` methods:
118
119 ```ts
120 const brand = await brandModuleService.updateBrands({
121 id: "brand_123",
122 metadata: {
123 category: "electronics",
124 },
125 })
126 ```
127
128 The brand record will now have the `metadata` property updated to include the new `category` property:
129
130 ```json title="Result"
131 {
132 "id": "brand_123",
133 "metadata": {
134 "category": "electronics"
135 }
136 }
137 ```
138
139 If you want to add another `is_featured` property later, you can do so by passing it in the update method again without affecting the existing properties:
140
141 ```ts
142 const brand = await brandModuleService.updateBrands({
143 id: "brand_123",
144 metadata: {
145 is_featured: true,
146 },
147 })
148 ```
149
150 The brand record will now have the `metadata` property updated to include both `category` and `is_featured` properties:
151
152 ```json title="Result"
153 {
154 "id": "brand_123",
155 "metadata": {
156 "category": "electronics",
157 "is_featured": true
158 }
159 }
160 ```
161
162 ### Update an Existing Property in the JSON Property
163
164 To update an existing property in the JSON property, pass the updated value in the `update` method.
165
166 Continuing with the Brand example, to update the `category` property in the `metadata`:
167
168 ```ts
169 const brand = await brandModuleService.updateBrands({
170 id: "brand_123",
171 metadata: {
172 category: "home appliances",
173 },
174 })
175 ```
176
177 The brand record will now have the `metadata` property updated to reflect the new `category` value, and existing properties will remain unchanged:
178
179 ```json title="Result"
180 {
181 "id": "brand_123",
182 "metadata": {
183 "category": "home appliances",
184 "is_featured": true
185 }
186 }
187 ```
188
189 ### Caveat: Updating Nested Objects
190
191 If you want to update a nested object within the JSON property, you need to provide the entire nested object in the update method.
192
193 For example, consider that you have a `details` object within the `metadata`:
194
195 ```json
196 {
197 "id": "brand_123",
198 "metadata": {
199 "category": "electronics",
200 "details": {
201 "warranty": "1 year",
202 "origin": "China"
203 }
204 }
205 }
206 ```
207
208 To update the `warranty` property within the `details` object, you need to provide the entire `details` object in the update method:
209
210 ```ts
211 const brand = await brandModuleService.updateBrands({
212 id: "brand_123",
213 metadata: {
214 details: {
215 warranty: "2 years",
216 origin: "China",
217 },
218 },
219 })
220 ```
221
222 The brand record will now have the `metadata` property updated with the new `warranty` value:
223
224 ```json title="Result"
225 {
226 "id": "brand_123",
227 "metadata": {
228 "category": "electronics",
229 "details": {
230 "warranty": "2 years",
231 "origin": "China"
232 }
233 }
234 }
235 ```
236
237 ### Remove a Property from the JSON Property
238
239 To remove a property from the JSON property, you can pass an empty string as the value of the property in the update method.
240
241 For example, to remove the `is_featured` property from the `metadata`:
242
243 ```ts
244 const brand = await brandModuleService.updateBrands({
245 id: "brand_123",
246 metadata: {
247 is_featured: "",
248 },
249 })
250 ```
251
252 The brand record will now have the `metadata` property updated to remove the `is_featured` property:
253
254 ```json title="Result"
255 {
256 "id": "brand_123",
257 "metadata": {
258 "category": "home appliances"
259 }
260 }
261 ```
262
263 <Note title="Tip">
264
265 Only an empty string removes a property. If you pass `null` as the value of a property, Medusa stores `null` as the property's value instead of removing it.
266
267 </Note>
268
269 ### Manage Metadata in Commerce Modules and Workflows
270
271 The merge behavior explained in this chapter also applies to the `metadata` property of data models in Medusa's Commerce Modules. This includes:
272
273 - Module service methods, such as the Product Module's `updateProducts`, the Order Module's `updateOrders` and `updateOrderLineItems`, and the Cart Module's `updateCarts` and `updateLineItems`.
274 - Workflows and steps that use these methods, such as `updateProductsWorkflow`, `updateOrderWorkflow`, `updateCartWorkflow`, and `updateCartsStep`.
275 - All API routes that are built on top of these workflows.
276
277 So, when you pass `metadata` to these API routes, methods, workflows, or steps:
278
279 - Medusa merges the top-level properties you pass with the existing `metadata`. Properties you don't pass remain unchanged.
280 - Medusa replaces nested objects entirely, as explained in the [Caveat: Updating Nested Objects](#caveat-updating-nested-objects) section. To change a single nested property, retrieve the record first, then pass the entire nested object with your changes.
281 - Medusa removes properties whose value is an empty string.
282
283 For example, to add a property to a product's `metadata` and remove another one using the `updateProductsWorkflow`:
284
285 ```ts
286 import { updateProductsWorkflow } from "@medusajs/medusa/core-flows"
287
288 // ...
289
290 const { result } = await updateProductsWorkflow(container)
291 .run({
292 input: {
293 products: [
294 {
295 id: "prod_123",
296 metadata: {
297 erp_id: "erp_123",
298 old_tax_code: "",
299 },
300 },
301 ],
302 },
303 })
304 ```
305
306 After the update, the product's `metadata` has the new `erp_id` property, doesn't have the `old_tax_code` property, and keeps all other existing properties.
307
308 ### Manage JSON Properties in API Routes
309
310 The instructions above also apply when managing JSON properties in API routes, since they typically use a service's `update` method under the hood.
311
312 Refer to the [API reference](!api!/store/manage-metadata) to learn more about managing JSON properties, such as `metadata`, in API routes.