# Data Store

`crm.dataStores`, `crm.dataStoreCollections`, `crm.dataStoreRecords` — `/v1/datastores`

A MongoDB — **yours**, registered with a credential, or **ours**, provisioned
for you in a location you pick. Either way you declare the collections and
fields you want and read and write records through the API: from a chatbot flow,
an automation, or your own code.

```ts
// your own cluster
await crm.dataStores.create({ title: 'Orders DB', credentials: { … } });

// or one of ours, no credential to manage
await crm.dataStores.create({ title: 'Leads', type: 'cloud' });
```

This runs as **its own service**, with its own database and its own deployment.
Nothing else in the platform depends on it, and it depends on nothing else: a
data store outage leaves contacts, the inbox and campaigns untouched, and the
connections it holds to customer clusters cannot crowd out anything but itself.

| Resource | Route | Scope |
| --- | --- | --- |
| [`dataStores`](#data-stores) | `/v1/datastores` | `datastores:read` / `datastores:write` |
| [`dataStoreCollections`](#collections) | `…/:store/collections` | `datastores:read` / `datastores:write` |
| [`dataStoreRecords`](#records) | `…/:store/collections/:collection/records` | `datastore-records:read` / `datastore-records:write` |

**Permissions** — three features, one per level:

| | Keys |
| --- | --- |
| stores | `CRM.DATASTORE`: `LIST`, `READ`, `CREATE`, `UPDATE`, `DELETE`, **`TEST`** |
| collections | `CRM.DATASTORE.COLLECTION`: `LIST`, `READ`, `CREATE`, `UPDATE`, `DELETE` |
| records | `CRM.DATASTORE.RECORD`: `LIST`, `READ`, `CREATE`, `UPDATE`, `DELETE` |

`TEST` is a verb of its own because testing a connection opens an outbound
connection to the customer's database, which is more than reading the row that
describes it. `READ` on a store exposes the connection target; the credential is
never returned.

On records, `search` is `LIST` (a read with a body), and the bulk endpoints are
the verb they perform — `bulk-update` is `UPDATE`, `bulk-delete` is `DELETE`.
`CRM.DATASTORE.RECORD` is the most consequential key here: it reads and writes
rows in the customer's own database.

## The model

Three things, nested:

```
data store            a database — yours by credential, or ours by request
└── collection        a schema: one collection name, and its fields
    └── records       the documents, in that database
```

## Two kinds of store

`type` on a store says whose database the records are actually in, and it is the
one decision here with consequences:

| | `self` *(default)* | `cloud` |
| --- | --- | --- |
| The database | Yours | Ours, provisioned per store |
| To create one | A credential, tested before anything is stored | Nothing. Optionally a `code` for the location |
| Reachability | Your cluster must be reachable from the internet, and usually needs our egress in its IP access list | Nothing to open, nothing to allow |
| System of record | You. Anything else with the credential writes the same documents | Us. The API is the only door |
| `remove()` on the store | Forgets the credential. **Your data stays** | **Drops the database.** The records are gone |

Pick `cloud` for data that does not already live somewhere — a form's
submissions, a chatbot's answers, a lookup table someone maintains in the panel.
Pick `self` when the data is already in your cluster, or has to stay there.

Everything past this point — collections, records, filters, paging — is
identical for both.

### Where a cloud store lives

```ts
const { data: regions } = await crm.dataStores.regions();
// [{ code: '6869Z798672Z296Z152Z286Z307', location: 'Germany' }]

const store = await crm.dataStores.create({
  title: 'Leads',
  type: 'cloud',
  code: regions[0].code,   // omit it and the platform picks its default
});

store.location; // 'Germany'
store.code;     // the cluster it is on — quote it in a support request
```

Read `regions()` rather than hardcoding a code: locations are added over time,
and an existing store **never moves** when one is added. That is why the code
comes back on the store itself, and it is the answer to a data-residency
question in writing.

An empty `regions()` means this deployment provisions none — an on-premise
install, typically — and a `type: 'cloud'` create is then a `422`.

Nothing about our cluster is returned on a cloud store: `host` and `username`
are empty, there is no `credentialType`, and `summary` is a label
(`cloud://Germany/ds_…`) rather than a connection string. There is no second way
into those records, by design.

## What `remove()` deletes

Worth stating before anything else, because the opposite assumption is the
expensive one in both directions:

| Call | What it removes |
| --- | --- |
| `dataStores.remove()` on a **`self`** store | The stored credential, and every schema on it. **Your database is untouched.** |
| `dataStores.remove()` on a **`cloud`** store | The schemas, and **every collection in its database — which destroys the database, irreversibly.** |
| `dataStoreCollections.remove()` | The schema. The collection and its documents remain, in either kind of store. |
| `dataStoreRecords.remove()` / `bulkRemove()` | Documents, irreversibly. |

For a `self` store: register the same credential again, declare the same
collection name, and all of it reads straight back. For a `cloud` store there is
nothing to re-register — the database was named after that store and a new one
is empty — so confirm with the user before calling it.

If a collection cannot be deleted, the call is a `502 datastore_purge_failed`
naming it, and **nothing** has been removed: the store and its schemas are
intact and the call can be retried once the cause is fixed.

## Errors from a cloud store say less, deliberately

On a **self** store an upstream failure carries the database's own message,
because the database is yours and the detail is the part you act on:

| Status | Code | |
| --- | --- | --- |
| 502 | `datastore_auth_failed` | The credential was refused. `details.reason` is the driver's message. |
| 502 | `datastore_unreachable` | No answer in time — usually an IP access list. |

On a **cloud** store every upstream failure is one code with no details:

| Status | Code | |
| --- | --- | --- |
| 502 | `datastore_unavailable` | The platform's cluster did not answer. Retry; there is nothing on your side to change. |

That is not vagueness for its own sake. Those messages name hosts, replica-set
members and database users belonging to the platform, none of which you can act
on and none of which an API should hand out. Refusals about **your request** —
a validation failure, a unique index, a 404 — are reported in full on both kinds
of store.

## What the platform holds

For a `self` store, **the credential and the schemas, and nothing else**. There
is no copy of your data here, no mirror and no sync: a record read is a live
query against your cluster, and a record write lands in it before the response
comes back.

Two consequences worth holding on to:

- **The platform is not the system of record.** Anything else holding those
  credentials — your own application, a colleague with Compass — writes the same
  documents. So a schema here is a *declaration*, not a guarantee: a document
  may carry fields it never mentioned, or lack ones it does.
- **Every record call costs a round trip to your database.** The connection
  stays open between calls, so that is one query's latency rather than a fresh
  TLS handshake each time — but a loop of a thousand single inserts is a
  thousand round trips. Send one `insert` with `records`.

For a `cloud` store the platform holds the database too, and the first
consequence does not apply: nothing else can write those documents. The second
still does — it is a different cluster, not a local one.

---

## Data stores

### Registering one

```ts
const store = await crm.dataStores.create({
  title: 'Orders DB',
  credentials: {
    type: 'field',
    host: 'cluster0.ab12c.mongodb.net',
    username: 'crm_writer',
    password: process.env.ORDERS_DB_PASSWORD!,
    database: 'shop',
  },
});
```

Or with a connection string, for anything the four fields cannot express — a
replica-set seed list, a non-standard port, TLS options:

```ts
await crm.dataStores.create({
  title: 'Orders DB',
  credentials: { type: 'string', uri: process.env.ORDERS_DB_URI! },
});
```

The URI **must name a database** (`mongodb+srv://user:pass@host/shop`). A URI
without one is legal Mongo and puts every document in a database called `test`,
which is a surprising place to find your records a month later, so it is refused
here instead.

### What happens before the row is written

1. The credential is checked for shape.
2. The host is resolved, and refused if it resolves somewhere private.
3. A connection is opened and pinged.
4. **Only then** is anything stored, with the secret encrypted.

So a `201` means your database really did accept those credentials. A store you
can see in the list is one that worked at least once.

| Status | Code | Meaning |
| --- | --- | --- |
| 422 | `validation_failed` | Malformed URI, a `host` with a scheme in it, no database named. |
| 422 | `invalid_datastore_host` | The host does not resolve, or resolves to a private address. |
| 502 | `datastore_auth_failed` | The database refused the username or password. |
| 502 | `datastore_unreachable` | No answer in time — usually an IP access list. |

### The host has to be reachable from the internet

A credential pointing at a private or loopback address is refused. The platform
would be connecting to *its own* network rather than to yours, so
`mongodb://localhost:27017` and `10.x`, `172.16–31.x`, `192.168.x`, `169.254.x`
are all rejected — including when a hostname you control resolves to one, since
the check is on the resolved address rather than on the string.

For `mongodb+srv` the SRV record is resolved first and its targets are checked,
which is also why a missing `_mongodb._tcp` record is reported as a bad host
rather than as a timeout thirty seconds later.

On Atlas you will usually also need to allow the platform's egress addresses in
your project's **IP access list**. Without that the symptom is
`502 datastore_unreachable` with a server-selection timeout, which looks like a
wrong host but is not.

### No credential ever comes back

```ts
store.summary;   // 'mongodb+srv://crm_writer:***@cluster0.ab12c.mongodb.net/shop'
store.host;      // 'cluster0.ab12c.mongodb.net'
store.username;  // 'crm_writer'
store.database;  // 'shop'
```

The password is encrypted at rest and is not returned in any form. `summary` is
the connection with the password replaced, which is what an edit screen needs in
order to show which database it is looking at. Host, user and database come back
in the clear because an edit form has to render them, and none of them opens a
connection on its own.

A cloud store takes no credentials at all:

```ts
await crm.dataStores.create({ title: 'Leads', type: 'cloud' });
```

Sending both is a `422`, as is a `code` on a `self` store: the two halves of the
body do not mix.

### Re-pointing one

```ts
await crm.dataStores.update(store.id, { title: 'Orders (production)' });

await crm.dataStores.update(store.id, {
  credentials: { type: 'string', uri: rotatedUri },
});
```

Credentials are replaced **whole or not at all**. There is no patching one field
of them: a host without its matching password is not a weaker credential, it is
a broken one. New credentials go through the same four steps as a create, and
the old connection is dropped — so the next record call reads from the new
cluster rather than from a connection that happens to still be open.

### Testing one

```ts
const { ok, database, collections, latencyMs } = await crm.dataStores.test(store.id);
```

The answer to "is it us or them". A credential that worked last month may have
been rotated, an Atlas project may be paused, an access list may have been
tightened — and each of those comes back as a different status code rather than
being inferred from a failing record call.

`collections` is also what you need to point a new schema at a collection that
already exists. It is **empty when the database user has no `listCollections`
privilege** — a least-privilege credential granted only `readWrite` legitimately
does not have it — so an empty list does not mean an empty database.

---

## Collections

A collection is a schema: one collection name inside your database, and the
fields it holds.

```ts
const customers = await crm.dataStoreCollections.create(store.id, {
  title: 'Customers',
  fields: [
    { name: 'Email', type: 'String' },
    { name: 'Signed Up', type: 'Date' },
    { name: 'Credits', type: 'Number', default: 0 },
    { name: 'Tags', type: 'Array' },
  ],
});

customers.collection;                       // '68f1c2a39b4e5d6f70812345_customers'
customers.fields.map((f) => f.name);        // ['email','signed_up','credits','tags']
```

### Field names are slugged, once

Punctuation is dropped, runs of spaces and hyphens become one underscore, and
the result is lowercased. `"First Name"` becomes `first_name`.

**Use the names the response gives you as your record keys.** That is the key
the document actually has. The legacy panel slugged the name when building its
schema but stored the original, so a field called `First Name` was stored under
`first_name` while the schema said `First Name` — and a record written against
the schema's spelling was silently dropped. Here only the slug is ever
persisted, so the two cannot disagree.

Two names that slug to the same thing (`"First Name"` and `"first_name"`) are
refused rather than letting the later one quietly win.

### The field types

| Type | Accepts | Notes |
| --- | --- | --- |
| `String` | a string; numbers and booleans are stringified | |
| `Number` | a number, or a numeric string | `NaN` and `Infinity` are refused: nothing compares equal to `NaN`, so a document holding one cannot be found by its own value |
| `Boolean` | `true`/`false`, `"true"`/`"false"`, `1`/`0` | |
| `Date` | an ISO string, or a unix timestamp in seconds or milliseconds | Read by magnitude, so both units work |
| `Array` | an array of anything | Untyped, because the legacy declaration was |

`default` applies when a record omits the field, and only on `String`, `Number`
and `Boolean`: a `Date` default would have to mean "now", which is a different
feature, and an `Array` default shared between documents is a trap.

### Pointing at a collection you already have

```ts
const existing = await crm.dataStoreCollections.create(store.id, {
  title: 'Orders',
  collection: 'orders',   // the collection already in your database
  fields: [{ name: 'order_no', type: 'String' }, { name: 'total', type: 'Number' }],
});
```

Omit `collection` and the server generates `<schema id>_<slugged title>`, which
cannot collide with anything already there. Supply it and the schema reads and
writes a collection you already have — which is how a database with data in it
gets used rather than duplicated. `dataStores.test()` lists the names.

It is **immutable afterwards**, and `update()` does not accept it. A schema
points at one collection for its whole life: every record ever written through
it lives there, and re-pointing it would orphan all of them. Point a *new*
schema at the other collection instead.

One schema per collection name per store, enforced by a unique index — two
schemas over one collection with different field declarations would mean a
record validating or not depending on which one it was written through.

### Declaring a collection does not create one

Mongo creates a collection on its first write. So a brand new schema addresses a
collection that is not there yet, and reads against it correctly return an empty
page rather than failing.

### Editing fields rewrites nothing

```ts
await crm.dataStoreCollections.update(store.id, customers.id, {
  fields: [...customers.fields, { name: 'plan', type: 'String', default: 'free' }],
});
```

`fields` replaces the whole list, and takes effect from the next call onward. It
does not migrate anything:

- **Dropping a field** stops it being writable and does not delete the data
  under that key. Re-declare the field and the values are there again.
- **Changing a type** leaves existing documents holding the old type. A
  `Number` field that used to be a `String` reads back strings for old records
  and numbers for new ones.
- **Adding a default** does not backfill. It applies to records inserted after.

---

## A record is a row, not a file

Records hold structured values. **Files are refused** — in a cloud store and in
your own alike, because the cost is the round trip and both pay it: every read
of a page carries every byte back through the API, with no cache and no
streaming, so one embedded image turns a 25-row page into a response nobody
wants. It is also storage nobody budgeted for, at a price object storage beats
by an order of magnitude.

So store the URL:

```ts
// no
await crm.dataStoreRecords.insert(store.id, collection.id, {
  record: { name: 'Badge', image: 'data:image/png;base64,iVBORw0KGgo…' },
});
// → 422 validation_failed { image: ["This looks like a file. …store its URL here"] }

// yes
await crm.dataStoreRecords.insert(store.id, collection.id, {
  record: { name: 'Badge', image: 'https://cdn.example.com/badges/42.png' },
});
```

What gets refused, with `422 validation_failed` keyed by the field:

| | |
| --- | --- |
| A `data:` URI | At any size — it can only be a file. |
| Base64 beginning with a file signature | PNG, JPEG, GIF, WebP, PDF, ZIP, MP3, MP4, WebM. Only checked on values of 64 characters or more, so a short string that happens to start that way is fine. |
| A raw file header | `%PDF-`, `GIF89a`, the PNG and JPEG magic bytes, a ZIP header. |
| `$binary`, `$uuid`, `$code`, `$function`, `$where` | Extended-JSON keys anywhere inside an `Array` value — binary and stored JavaScript by another route. |
| A value over **16KB** | Serialised. Roughly four thousand words in one field. |
| A record over **64KB** | The finished document, so a hundred legal fields cannot add up to an illegal row. |
| An array over **1000 items**, or nested deeper than **8** | A list of options, not a dataset. |

`insert`, `update` and `bulkUpdate` all go through the same check.

## Records

Documents in your database.

```ts
await crm.dataStoreRecords.insert(store.id, customers.id, {
  record: { email: 'a@example.com', signed_up: '2026-10-14T09:00:00Z', tags: ['vip'] },
});

await crm.dataStoreRecords.insert(store.id, customers.id, {
  records: rows,   // up to 1000
});
```

### Writes are validated against the declaration

Keys must be declared field names, and values are coerced to the declared type —
`"42"` into a `Number` field is stored as `42`, an ISO string into a `Date` field
as a real date.

An **undeclared key is a 422 that names it**:

```json
{
  "error": {
    "code": "validation_failed",
    "details": {
      "fieldErrors": {
        "unknown_fields": ["Not declared on this collection: emial. Declared fields are: email, signed_up, credits, tags"]
      }
    }
  }
}
```

This is the one deliberate break from the legacy endpoint. There, a mongoose
schema with `strict: true` *dropped* unknown keys, so a record posted with
`emial` returned success having stored nothing under either spelling — and
nobody noticed for as long as nobody went looking.

| Key | On the way in |
| --- | --- |
| a declared field | coerced to its type |
| `null` | clears the field |
| `created_on`, `updated_on` | ignored — the server stamps them |
| `id`, `_id` | refused: the database assigns the id |
| anything else | **422**, naming it |

`created_on` and `updated_on` are unix **seconds**, or real `Date`s if the
collection declared them with `type: 'Date'`. `created_on` is written once;
`updated_on` moves on every update, and an update cannot move `created_on`.

### Inserting many

```ts
const { inserted, ids } = await crm.dataStoreRecords.insert(store.id, orders.id, {
  records: rows,
});
```

A batch is **unordered**: one document rejected by a unique index of yours does
not abandon the rest, so `inserted` can be lower than what you sent. `ids` come
back in the order the documents went out.

### Reading

```ts
const { data, pagination } = await crm.dataStoreRecords.list(store.id, orders.id, {
  rows: 50,
  sort: 'total',
  order: 'desc',
});
```

| Query | Default | Notes |
| --- | --- | --- |
| `page` | `1` | 1-based. |
| `rows` | `25` | 1–100. |
| `sort` | `created_on` | Any field name. |
| `order` | `desc` | |

`_id` is appended to the sort as a tiebreaker, so paging is reproducible even
when the sort field repeats — or does not exist at all, which it will not on an
adopted collection something else wrote. Without that, offset paging over tied
values can return the same document on two pages and skip another entirely.

**Reads return every stored key**, declared or not. The documents are yours and
may have been written by something else; hiding your own data because our
declaration is incomplete would be worse than surprising. `_id` reads back as
`id`, and dates as ISO strings.

### Searching

```ts
const { data } = await crm.dataStoreRecords.search(store.id, orders.id, {
  filter: {
    $or: [{ status: 'open' }, { total: { $gte: 100 } }],
    created_on: { $gte: '2026-10-01' },
    tags: 'vip',
  },
  sort: 'total',
  order: 'desc',
});
```

A real Mongo filter — `$in`, `$gt`, `$or`, `$nor`, `$not`, `$regex`, `$exists`,
`$elemMatch`, all of it. It is your database: there is nothing in it you do not
already own, so narrowing the query language would only cost you expressiveness.

A POST rather than a GET because a Mongo filter is a nested object, and encoding
one into a query string is a different argument in every HTTP client. It reads
and changes nothing.

**Operands are coerced per declared field** before the query is sent, which is
the difference between a filter that works and one that silently matches
nothing:

| Filter | Against | What is actually sent |
| --- | --- | --- |
| `{ created_on: { $gte: '2026-10-01' } }` | a `Date` field | a real `Date` |
| `{ total: { $gt: '100' } }` | a `Number` field | `100` |
| `{ id: '68f1c2…' }` | — | `{ _id: ObjectId('68f1c2…') }` |
| `{ tags: 'vip' }` | an `Array` field | unchanged — "contains" |

`id` works as an alias for `_id` and takes the string form, because `id` is the
name every record reads back with.

Three operators are refused wherever they appear, at any depth:

| Status | Code | Meaning |
| --- | --- | --- |
| 422 | `filter_operator_not_allowed` | `$where`, `$function` or `$accumulator` — each runs JavaScript on your cluster. |
| 422 | `filter_too_complex` | Nested deeper than 10 levels, or more than 500 keys. |
| 422 | `validation_failed` | An operand that cannot be coerced — `{ total: { $gt: 'abc' } }` on a `Number` field. |

A value that cannot be coerced is reported rather than quietly matching nothing.

### Updating

```ts
await crm.dataStoreRecords.update(store.id, orders.id, record.id, {
  record: { status: 'shipped', tracking: 'XY123' },
});
```

A `$set` of those fields and nothing else. Keys you leave out are untouched,
`null` clears a value, and the response is the record as it is after the write.
Validation is identical to an insert.

There is no `$inc`, `$push` or `$rename`: an update here is "these fields now
have these values", which is what every caller of the legacy endpoint was doing
— it wrapped the body in `$set` too — and it keeps an update subject to the same
field validation as an insert.

### Bulk update and delete

```ts
const { matched, modified } = await crm.dataStoreRecords.bulkUpdate(store.id, orders.id, {
  filter: { status: 'pending', created_on: { $lt: cutoff } },
  update: { status: 'expired' },
});

const { deleted } = await crm.dataStoreRecords.bulkRemove(store.id, orders.id, {
  filter: { status: 'expired' },
});
```

**The filter cannot be empty.** `{}` matches the whole collection, and a
one-character slip that rewrites or deletes every record is not something to
make convenient — emptying a collection deliberately means paging through it.

`modified` is lower than `matched` where a record already held the values being
written, which is worth seeing rather than collapsing into one number.

---

## Isolation

Records carry no tenant field. They are not ours to stamp — they are documents
in your database, often ones that existed before you registered it.

So isolation is the **resolution order**, and it is the same on every record
call:

1. The store is resolved inside the calling account.
2. The collection is resolved inside that store.
3. Only then is a connection acquired and a query sent.

A store id from another account is a `404`. A collection id from another store —
including another of your own — is a `404`. Never a `403`: that would confirm
the id exists.

## Connections

One connection per distinct credential, shared by every request using it, with a
small driver pool inside it. Idle connections close after ten minutes and the
least recently used one closes when the cache is full; both are invisible to
callers, since the next call reconnects.

This is worth knowing for one reason: the platform holds open connections to
your cluster while you are using it. They count against your Atlas connection
limit, alongside your own applications. The per-credential pool is deliberately
small for that reason.

The legacy implementation opened a **new connection for every single
operation** and closed it afterwards — a TCP handshake, a TLS handshake, a SCRAM
exchange and two DNS lookups before each query, and nothing bounding how many
existed at once. A busy flow could exhaust a customer's own connection limit.

## Not here

- **No aggregation.** A pipeline can read other collections with `$lookup` and
  write them with `$merge`, which makes a schema's boundary meaningless, and
  `$function` runs JavaScript on your cluster. Use your own credentials and your
  own driver for that — it is your database.
- **No index management.** Create indexes on your own cluster. Any unique index
  you create is enforced on writes through this API, and a violation comes back
  as a `422` quoting the database's own message.
- **No bulk import from a file.** `insert` with `records` is the batch path,
  1000 at a time.
