> ## Documentation Index
> Fetch the complete documentation index at: https://doc.trackrev.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Referral credits with MongoDB

> End-to-end setup for a product-credit referral programme when your users live in MongoDB — connect the collection, then enroll and report signups through the API.

This is the complete, MongoDB-specific walkthrough for a **credit** referral programme: your
referrers earn in-product credit, and TrackRev writes that credit straight into your `users`
collection. Nothing here is Mongo-only except **Half 1** — the API calls in **Half 2** are the same
for every database.

<Info>
  There are two halves that must agree. The **API calls** create the credit; the **MongoDB connector**
  delivers it into your collection. The value that ties them together is `external_user_id`.
</Info>

Throughout, assume your users look like this:

```js theme={null}
// database: "production", collection: "users"
{ _id: ObjectId("66f…"), email: "alice@example.com", credits: 0 }
```

## Half 1 — Connect MongoDB (delivery, one time)

Open **Configuration → Integrations → Credit fulfilment**, choose **MongoDB**, and fill in:

| Field             | Example                                       | What it is                                       |
| ----------------- | --------------------------------------------- | ------------------------------------------------ |
| Connection string | `mongodb+srv://user:pass@cluster.mongodb.net` | Use a database user with **write** access        |
| Database name     | `production`                                  |                                                  |
| Users table       | `users`                                       | your **collection** name                         |
| **Match column**  | `_id`                                         | the field `external_user_id` is compared against |
| Credit column     | `credits`                                     | numeric field credits are added to               |

<Warning>
  **Allow network access.** TrackRev connects from serverless functions with no fixed IP. On **MongoDB
  Atlas → Network Access → IP Access List**, add `0.0.0.0/0` (or use PrivateLink / a static-egress
  proxy). Without it, saving connects to nothing and **Test connection** fails with a *server selection
  timeout*.
</Warning>

Then click **Test connection** — it should go healthy. (Test proves TrackRev can reach and read your
database; it does not exercise the match column, so also confirm the first real referral lands.)

### The one rule that makes it work

Whatever you send as **`external_user_id`** in the API **must equal the value stored in your
`match_column`**. Pick one of these and stay consistent:

<CardGroup cols={2}>
  <Card title="Match on _id" icon="fingerprint">
    Set **Match column** to `_id` and enroll users with their Mongo `_id` string as
    `external_user_id`. TrackRev matches `{ _id: ObjectId(external_user_id) }`.
  </Card>

  <Card title="Match on email" icon="envelope">
    Set **Match column** to `email` and enroll users with their email as `external_user_id`.
    TrackRev matches `{ email: external_user_id }`.
  </Card>
</CardGroup>

The connector matches an `_id` ObjectId, a string id, or a numeric id automatically — the credit
field may be a number, or missing/null (it starts from 0). It just has to be the **same identifier**
on both sides.

## Half 2 — Wire the API in your app

### 1. Install the pixel

```html theme={null}
<script async src="https://app.trackrev.io/p.js" data-id="YOUR_WORKSPACE_ID"></script>
```

Tracks clicks and keeps the visitor id (`_vid`) alive across the visit.

### 2. Enroll each user to mint their referral link

```bash theme={null}
curl -X POST https://app.trackrev.io/api/v1/referrals/enroll \
  -H "Authorization: Bearer sk_live_YOUR_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "alice@example.com",
    "external_user_id": "66f…",     // Alice's Mongo _id — matches your Match column
    "tier": "paid"
  }'
# → { "referral_link": "https://you.trackrev.io/abc123", ... }
```

Show `referral_link` to the user. (Or drop `widget.js`, which enrolls and renders a share card for
you.)

### 3. Report the signup when a referred friend joins

The friend clicks the link, lands on your site with `?_vid=…`, and you store it. When they create
their account, call:

```bash theme={null}
curl -X POST https://app.trackrev.io/api/v1/referrals/report-signup \
  -H "Authorization: Bearer sk_live_YOUR_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "new_user_external_user_id": "70a…",   // the new user's Mongo _id
    "email": "bob@example.com",
    "_vid": "SAVED_VID"
  }'
# → { "matched": true }   ← a credit is now created for Alice (the referrer)
```

This is the call that actually creates the reward. `_vid` is the resolver, but you can also send
`ref_code` (the link slug) or `referrer_external_user_id` instead.

## What happens automatically

TrackRev creates the credit grant, then the fulfilment cron runs the MongoDB connector against your
collection:

```js theme={null}
db.collection("users").updateOne(
  { _id: ObjectId("66f…") },   // Match column = external_user_id
  [ { $set: { credits: { $add: [ { $ifNull: ["$credits", 0] }, 50 ] } } } ]
)
```

Alice's `credits` goes `0 → 50`. No delivery code on your side.

## Verify end to end

<Steps>
  <Step title="Enroll user A">
    Call `enroll` for user A and copy the returned `referral_link`.
  </Step>

  <Step title="Click + sign up as user B">
    Open the link in a private window (`?_vid=…` appears in the URL), then sign up as B.
  </Step>

  <Step title="Report B's signup">
    Your backend calls `report-signup` with B's id and the saved `_vid`.
  </Step>

  <Step title="Check MongoDB">
    A's `credits` field has increased — proof the loop closed.
  </Step>
</Steps>

<Tip>
  If credits appear in the dashboard but never reach the collection, it's almost always the Atlas IP
  Access List (add `0.0.0.0/0`) or a `match_column` that doesn't match the `external_user_id` you
  enrolled with. See the connector's **last error** on the Fulfilment page.
</Tip>

The [credit rewards & fulfilment](/affiliate/credits-and-fulfilment) page covers the other connectors
(Supabase, Postgres, Airtable, Webhook); the API steps above are identical for all of them.
