Skip to main content

Connect to CouchDB

CouchDB is an open-source NoSQL document database that uses JSON to store data and JavaScript for queries. With Retool's CouchDB integration, you can build apps and automations that read documents, insert new data, update records, and query using Mango Query syntax.

ARCADE_DEMO_HERE

What you can do with CouchDB

  • Query documents - Retrieve documents by ID or use Mango Query for complex searches.
  • Insert documents - Create new JSON documents in your databases.
  • Update documents - Modify existing documents with revision tracking.
  • Delete documents - Remove documents from databases.
  • Use views - Query design document views for aggregated data.

Before you begin

To connect CouchDB to Retool, you need the following:

  • CouchDB instance - A running CouchDB server accessible over the internet.
  • Host and port - The hostname or IP address and port (default: 5984).
  • Database credentials - Username and password with appropriate permissions.
  • Network access - CouchDB server must be accessible from Retool Cloud IP addresses.
  • Retool permissions - Ability to create and manage resources in your organization.

Create a CouchDB resource

Follow these steps to create a CouchDB resource in your Retool organization.

1. Create a new resource

In your Retool organization, navigate to Resources in the main navigation and click Create newResource. Search for "CouchDB" and click the CouchDB tile to begin configuration.

Use folders to organize your resources by team, environment, or data source type. This helps keep your resource list manageable as your organization grows.

2. Configure connection settings

Configure the following connection settings for your CouchDB resource.

Resource name

Give your resource a descriptive name that indicates which database or environment it connects to.

Example
// Descriptive resource names
production_couchdb
user_data_db
documents_couchdb

Host

The hostname or IP address of your CouchDB server.

Example
// Cloud-hosted CouchDB
couchdb.example.com

// Local development
localhost

// IP address
192.168.1.100

// Dynamic from dropdown
{{ serverSelect.value }}

Port

The port number for your CouchDB server. The default port is 5984.

Example
// Default CouchDB port
5984

// Custom port
8080

SSH tunnel

Enable SSH tunneling if your CouchDB server is only accessible through an SSH bastion host. This creates a secure tunnel through an intermediate server.

Outbound region

If your organization uses outbound regions, select the region that should be used for requests to CouchDB. This controls which geographic region your requests originate from.

3. Configure authentication

CouchDB uses username and password authentication.

Username

The username for authenticating with your CouchDB server. This user should have appropriate permissions for the databases you want to access.

Password

The password for the CouchDB user account.

CouchDB supports role-based access control. Ensure your user has the necessary permissions (read, write, admin) for the databases you want to query.

4. Configure SSL settings

Enable SSL/TLS to encrypt the connection between Retool and your CouchDB server.

Use SSL

Enable this option if your CouchDB server uses HTTPS. Most production CouchDB instances should use SSL for secure communication.

SSL certificate

If your CouchDB server uses a self-signed certificate, you can provide the certificate here. Leave empty for standard certificates.

5. Test the connection

Click Test connection to verify Retool can authenticate with CouchDB. If the test succeeds, you see a success message. If it fails, check the following:

  • Host and port - Verify the hostname and port are correct and the server is running.
  • Credentials - Ensure the username and password are correct.
  • Network access - Confirm your CouchDB server is accessible from Retool (check firewall rules and security groups).
  • SSL configuration - If using SSL, verify the certificate is valid.

After testing the connection, click View in console to open the Debug Tools console. The console displays detailed information about the test, including the test query executed and its response, execution time, and error details if the test fails. This information is helpful for troubleshooting connection issues.

6. Save the resource

Click Create resource to save your CouchDB resource. You can now use it in queries across your Retool apps and automations.

Query CouchDB data

Once you've created a CouchDB resource, you can query documents in your Retool apps and automations.

Create a query

To create a CouchDB query in an app:

  1. In the Retool app IDE, open the Code tab, then click + in the page or global scope.
  2. Select Resource query.
  3. Choose your CouchDB resource.
  4. Select a Method from the dropdown.

You can also create CouchDB queries in workflows and agent tools using the same resource.

Query methods

CouchDB queries support multiple methods for different operations:

MethodDescriptionUse Case
GetRetrieve a document by ID.Display a specific document.
InsertCreate a new document.Add new records from forms.
UpdateModify an existing document.Update records with inline editing.
DeleteRemove a document.Delete unwanted records.
FindQuery documents using Mango Query.Search and filter documents.
Get ViewExecute a design document view.Retrieve aggregated or indexed data.

Query configuration fields

Each query method has specific configuration fields:

Database

The name of the CouchDB database to query.

Database example
// Static database name
users

// Database from dropdown
{{ databaseSelect.value }}

// Database from table selection
{{ table1.selectedRow.data.database_name }}

Document ID

The unique identifier (_id) for the document. Required for get, update, and delete operations.

Document ID example
// Static ID
user_12345

// From table selection
{{ table1.selectedRow.data._id }}

// From input
{{ userIdInput.value }}

// Generated ID
{{ 'user_' + moment().unix() }}

Document value

The JSON document to insert or update. For insert operations, this is the complete document. For update operations, provide the modified fields.

Document value example
// From form component
{{ form1.data }}

// Manual JSON structure
{
"name": {{ nameInput.value }},
"email": {{ emailInput.value }},
"created_at": {{ moment().toISOString() }},
"status": "active"
}

// Update specific fields
{
"_id": {{ table1.selectedRow.data._id }},
"_rev": {{ table1.selectedRow.data._rev }},
"status": {{ statusSelect.value }}
}

Revision

The document revision (_rev) for update and delete operations. CouchDB uses revisions for conflict detection and must be provided when modifying documents.

Revision example
// From existing document
{{ table1.selectedRow.data._rev }}

// From previous query
{{ getDocQuery.data._rev }}

Mango Query

A JSON query using Mango Query syntax for the find method. Mango Query is similar to MongoDB query syntax.

Mango Query example
// Find by field value
{
"selector": {
"status": "active"
}
}

// Multiple conditions
{
"selector": {
"status": "active",
"age": { "$gt": 18 }
},
"limit": 10
}

// Complex query with operators
{
"selector": {
"$and": [
{ "type": "user" },
{ "created_at": { "$gte": "2026-01-01" } }
]
},
"sort": [{ "created_at": "desc" }],
"limit": 100
}

// Dynamic query from inputs
{
"selector": {
"status": {{ statusSelect.value }},
"department": {{ departmentSelect.value }}
}
}

View URL

The path to a design document view for the getView method. Views are predefined queries stored in design documents.

View URL example
// Basic view
_design/users/_view/by_status

// View with design document
_design/analytics/_view/monthly_totals

// Dynamic view selection
{{ '_design/users/_view/' + viewSelect.value }}

Query options

Additional options for controlling query behavior.

Limit - Maximum number of documents to return.

Limit example
// Static limit
100

// From input
{{ limitInput.value }}

// Pagination
{{ table1.pageSize }}

Skip - Number of documents to skip (for pagination).

Skip example
// Calculate offset for pagination
{{ (table1.page - 1) * table1.pageSize }}

// Static skip
50

Include docs - Whether to include full document content in view results. Enable this to get complete documents instead of just keys and values.

Start key / End key - Range query parameters for views. Used to filter view results by key range.

Start key / End key example
// Date range
// Start key: ["2026-01-01"]
// End key: ["2026-12-31"]

// Compound key range
// Start key: ["user", "2026-01-01"]
// End key: ["user", "2026-12-31"]

Common use cases

These examples demonstrate the most common CouchDB operations in Retool apps.

Query and display documents

Use Mango Query to search for documents and display them in a Table component.

Query configuration:

Method: Find
// Database: users
// Mango Query:
{
"selector": {
"status": "active"
},
"limit": 100
}

Table component:

Set the Table component's Data property to {{ couchdbQuery.data.docs }} to display the documents.

Tips:

  • Use the docs property of the result to access the document array.
  • Enable pagination by adjusting the limit and skip values.
  • Add search functionality by making the selector dynamic based on user input.
Insert documents from a form

Collect user input in a Form component and insert it as a new CouchDB document.

1. Create a Form component:

Add a Form component with fields matching your document structure (e.g., name, email, department, status).

2. Create insert query:

Method: Insert
// Database: users
// Document value:
{
"_id": {{ 'user_' + moment().unix() }},
"name": {{ form1.data.name }},
"email": {{ form1.data.email }},
"department": {{ form1.data.department }},
"status": "active",
"created_at": {{ moment().toISOString() }}
}

3. Add event handler:

Add an event handler to the Form component's Submit event that runs the insert query, shows a success notification, and resets the form.

Result: When users submit the form, a new document is created in CouchDB with a unique ID.

Update documents with inline editing

Allow users to edit documents directly in a Table component and save changes.

1. Enable table editing:

Set the Table component's Editable property to {{ true }} and configure which columns are editable.

2. Create update query:

Method: Update
// Database: users
// Document ID: {{ table1.selectedRow.data._id }}
// Revision: {{ table1.selectedRow.data._rev }}
// Document value:
{
"_id": {{ table1.selectedRow.data._id }},
"_rev": {{ table1.selectedRow.data._rev }},
"name": {{ table1.changesetObject.name || table1.selectedRow.data.name }},
"email": {{ table1.changesetObject.email || table1.selectedRow.data.email }},
"status": {{ table1.changesetObject.status || table1.selectedRow.data.status }}
}

3. Add save button:

Add a Button component with an event handler that runs the update query when clicked.

Result: Users can edit cells directly in the table, and clicking save updates the document in CouchDB with proper revision tracking.

Delete documents with confirmation

Delete documents from CouchDB with user confirmation.

1. Add delete button:

Add an action column to your Table with a delete button in each row.

2. Create delete query:

Method: Delete
// Database: users
// Document ID: {{ table1.selectedRow.data._id }}
// Revision: {{ table1.selectedRow.data._rev }}

3. Add confirmation dialog:

Configure the delete button's event handler to show a confirmation dialog before running the delete query.

Result: Users can delete documents, but must confirm the action before deletion occurs.

Use views for aggregated data

Query a CouchDB view to get aggregated or indexed data.

1. Create view query:

Method: Get View
// Database: analytics
// View URL: _design/reports/_view/sales_by_month
// Include docs: false
// Limit: 12

2. Display in chart:

Use the view results in a Chart component to visualize aggregated data:

// Chart data
{{ couchdbViewQuery.data.rows.map(row => ({
month: row.key,
total: row.value
})) }}

Result: Display aggregated data from CouchDB views in charts or tables without querying individual documents.

Data types and formatting

CouchDB stores all data as JSON documents with automatic type preservation.

Reading data

When reading documents from CouchDB, Retool preserves the JSON data types.

Data TypeDescription
StringsText values returned as JavaScript strings.
NumbersNumeric values returned as JavaScript numbers. CouchDB supports integers and floating-point numbers.
BooleansBoolean values returned as true or false.
ArraysJSON arrays returned as JavaScript arrays.
ObjectsNested objects returned as JavaScript objects.
NullNull values returned as null.

Writing data

When writing documents to CouchDB, Retool converts JavaScript values to JSON.

Value TypeDescription
StringsWritten as JSON strings.
NumbersWritten as JSON numbers.
BooleansWritten as JSON booleans (true or false).
ArraysWritten as JSON arrays.
ObjectsWritten as JSON objects. Nested objects are preserved.
DatesJavaScript Date objects must be converted to ISO 8601 strings using moment().toISOString().
UndefinedUndefined values are omitted from the document.

Document metadata

CouchDB documents include special metadata fields:

FieldDescription
_idUnique document identifier. Required for all documents. Can be auto-generated or user-specified.
_revDocument revision identifier. Required for update and delete operations. Format: 1-abc123....
_deletedBoolean flag indicating if document is deleted (only in replication).

Best practices

Follow these best practices to optimize performance, maintain security, and ensure data integrity when working with CouchDB.

Security

  • Use configuration variables: Store database credentials in configuration variables or rather than hardcoding them in resources or queries.
  • Use resource environments: Organizations on an Enterprise plan can configure multiple resource environments to maintain separate database configurations for production, staging, and development.
  • Enable SSL/TLS: Use SSL/TLS encryption for connections to protect data in transit.
  • Apply least privilege: Grant database users only the minimum permissions needed for their operations. Use read-only users for queries that only need to read data.
  • Validate user input: Always validate and sanitize user input before using it in queries to prevent injection attacks.

Data integrity

  • Handle revision conflicts: CouchDB uses optimistic locking with _rev. Always check for and handle conflicts when updating or deleting documents.
  • Validate before delete: Always show confirmation dialogs before executing delete operations to prevent accidental data loss.
  • Use views wisely: CouchDB views are eventually consistent. For critical operations, verify data state after view queries.
  • Handle errors gracefully: Configure error notifications and fallback behavior for failed queries to improve user experience.