Document Model
As a datastore that leverages conflict-free replicated data type (CRDT) technology to enable advanced sync capabilities, the foundation of each document is represented as a CRDT map. That is, when you invoke the Upsert method and create a new document object, you form a top-level map object at its root.
For example, the following snippet of a basic JSON-like document object actually represents a single map object:
{
"_id" "123abc",
"name": "Sam",
"age": 45,
"isOnline": false
}If you need to represent a highly complex dataset in a document, you can embed a map within another map. For more information, see Embedding Map Structures, as follows.
Embedding Map Structures
Embedding a map provides a way for you 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, within another map, and so on.
You can model relationships between your data using foreign-key and key-value relationships by way of embedded maps and arrays. For more information, see Relationships.
For example, the following snippet shows three levels of embedded maps: details, engine, interior, and features.
{
"_id": "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 own key-value pairs and, if used, children-level maps. You can represent key values using a register, counter, array, or another map. For more information, see Data Types.
Benefits of Embedding Maps
Embedding maps 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.
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:
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.collection('orders').upsert(order);