---
title: Relationships
slug: v4-6/document-model/relationships
docTags: 
createdAt: 2023-10-05T13:25:28.790Z
---

There are several methods for linking related data items and organizing them for easy lookup:

- Field referencing another document by `_id`.&#x20;
- Embedded JSON object that acts as a `REGISTER` type or an embedded `MAP`.&#x20;

# Overview

The following table provides a complete overview of the different relationships you can form in Ditto, as well as a brief description, list of possible approaches you can take, and links to related content:

| **Relationship** | **Description**                                                                                                                                                      | **Approaches**                                                                                                                          |
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| One-to-many      | Associates a parent element with children elements to establish a hierarchy.                                                                                         | - Embed a JSON object (`REGISTER`)
- Embed a `MAP`
- Reference a field to a document&#x20;
- Reference a document to a collection&#x20; |
| Many-to-many     | Associates multiple entities in one collection with multiple entities in another collection.                                                                         | *  Embed a JSON object (`REGISTER`)
* Embed a `MAP`
* Create references between documents in different collections                      |
| Many-to-one      | Associates two or more collections, where one collection refers to the primary key of another collection to create a meaningful relationship between the datasets.   | - Embed a JSON object (`REGISTER`)
- Embed a `MAP`
- Create references between documents in different collections                       |

:::hint{type="warning"}
Avoid using `arrays` in Ditto.&#x20;

Due to potential merge conflicts when offline peers reconnect to the mesh and attempt to sync their updates, especially when multiple peers make concurrent updates to the same item within the `array`.
:::

# Foreign-Key Relationships

To create a *foreign-key relationship*, store the primary key to one document within another document.&#x20;

A foreign-key relationship establishes a link between two or more datasets. For example, the following snippet demonstrates a foreign-key relationship between documents in the `cars` and `people` collections, in which the reference to `susanId` serves as the foreign key establishing a relationship between `cars` and `people`:

:::CodeblockTabs
pseudocode

```javascript
const results = await ditto.store.write(async (transaction) => {
   // Create a person named Susan in the "people" collection
  const cars = transaction.scoped('cars')
  const people = transaction.scoped('people')

  // Create a car document in the "cars" collection
  const susanId = await people.upsert({
    name: 'Susan',
  })
  await cars.upsert({
    make: 'Hyundai',
    color: 'red',
    owner: susanId, // Set the owner field to Susan's ID
  })
  
  // Evict the Susan document from the "people" collection
  await people.findByID(susanId).evict()
})
```
:::

# Key-Value Relationships

A *key-value relationship&#x20;*&#x65;stablishes a parent-child hierarchy between embedded data elements. In this hierarchy, the key functions as the parent, and its encapsulated values, represented as a set of key-value pairs, serve as children.&#x20;

When managing data that requires unique identifiers and relationships, instead of using an `array` to encode your data, use a `MAP` with unique string keys and object values instead.&#x20;

If you need to represent a highly complex dataset in a document, you can embed a `MAP` data type within a document.

:::hint{type="warning"}
Avoid using `arrays` in Ditto.&#x20;

Due to potential merge conflicts when offline peers reconnect to the mesh and attempt to sync their updates, especially when multiple peers make concurrent updates to the same item within the `array`.
:::

# Deeply-Hierarchical Structures

Embedding a `MAP` is one way to structure and organize related data within a single document to create a complex structure with multiple levels of hierarchy. As in, you can embed a `MAP` within a `MAP`, within another `MAP`, and so on.&#x20;

:::hint{type="info"}
For an example demonstrating both the deeply embedded and flat models, see [Bad Pattern: Large Documents](docId\:vk4CuQuMAwQFv0hEyATIt).
:::

For example, the following snippet shows three levels of embedded `maps`: `details`, `engine`, `interior`, and `features`.&#x20;

```json
{
  "_id": {
    "vin": "123abc",
    "make": "Toyota",
    "model": "Corolla",
    "year": 2022,
  },
  "details": {
    "engine": {
      "type": "Gasoline",
      "displacement": "1.8L"
    },
    "interior": {
      "seats": 5,
      "color": "Black"
    },
    "features": {
      "safety": {
        "airbags": 6,
        "antilockBrakes": true
      },
      "technology": {
        "infotainment": "Touchscreen",
        "navigation": true
      }
    }
  }
}

```

Each level contains its key-value pairs and, if used, children-level `MAP`. You can represent key values using a `REGISTER`, `ATTACHMENT`, or another `MAP`. 

***

# Benefits of Embedding Maps

Embedding a `MAP` is beneficial in scenarios where you need to manage a collection of items and continuously modify that collection over time; that is you want to link multiple data items with a single unique `string` identifier, but you anticipate that these data items are subject to concurrent edits over time.&#x20;

As an example, the following snippet demonstrates a basic Point-of-Sale (PoS) system where you need to keep track of the customer `orders` collection. And, since multiple users can add and remove orders within the collection, you embed a map to represent the ordered items, where each key denotes an item ID and the linked value indicates the quantity ordered:

:::CodeblockTabs
pseudocode

```javascript
const order = {
  customerName: 'John Doe',
  orderDate: '2023-08-15',
  items: {
    'item123': 2, // Item ID: Quantity ordered
    'item456': 5,
    'item789': 1
  }
};

// Inserting the order into the Ditto collection
await ditto.store.execute(`
  UPDATE INTO orders
  DOCUMENTS (:order)`,
  { order });
```
:::

