Skip to main content
skill CX Codex

cloudbase-document-database-web-sdk — Claude Code skill: install

A skill for browser-side CloudBase document database work with @cloudbase/js-sdk, covering CRUD, queries, pagination, and realtime listeners.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add TencentCloudBase/skills --skill cloudbase-document-database-web-sdk -a claude-code
Open on GitHub

What cloudbase-document-database-web-sdk does

This skill guides Web application code that accesses CloudBase Document Database through @cloudbase/js-sdk. It covers reading, inserting, updating, and removing documents, plus compound queries, pagination, aggregation, geolocation, and watch() listeners.

Its guidance routes work to focused references for CRUD, queries, pagination, aggregation, realtime updates, and security rules. The recommended setup keeps one shared app and db instance. Resource administration belongs to MCP tools rather than application-level SDK code.

A collection that requires user identity can reject requests made before sign-in. Work involving PostgreSQL, CloudBase PG, or app.rdb() is routed to postgresql-development; existing NoSQL collections in the same environment stay within this skill’s scope.

What it helps with

  • read CloudBase documents from a Web app
  • create, update, and remove collection records
  • add pagination to a larger collection
  • wire realtime changes through watch()
  • separate SDK code from resource administration

Example prompts for the agent

  • Use @cloudbase/js-sdk and implement collection CRUD through app.database().
  • Add pagination and a compound query for a CloudBase collection in the browser code.
  • Set up watch() for realtime changes and check the collection’s auth requirements.

How to install cloudbase-document-database-web-sdk

1Skills CLI (Vercel)

npx skills add TencentCloudBase/skills --skill cloudbase-document-database-web-sdk -a claude-code

2Manually: put the files in place

~/.claude/skills/cloudbase-document-database-web-sdk/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/cloudbase-document-database-web-sdk/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about cloudbase-document-database-web-sdk

How do I install cloudbase-document-database-web-sdk in Claude Code?

Run npx skills add TencentCloudBase/skills --skill cloudbase-document-database-web-sdk -a claude-code, then check ~/.claude/skills/cloudbase-document-database-web-sdk/SKILL.md.

What does cloudbase-document-database-web-sdk do?

It guides browser-side CloudBase Document Database code with @cloudbase/js-sdk, including CRUD, queries, pagination, aggregation, geolocation, and realtime listeners.

Can I use this skill for CloudBase PostgreSQL?

New CloudBase PG tables should use postgresql-development with app.rdb(). This skill is for confirmed NoSQL collection work, while existing NoSQL collections in the same environment remain in scope.

Source text

SKILL.md · MIT
---
name: cloudbase-document-database-web-sdk
description: Use CloudBase document database Web SDK only for confirmed NoSQL collection work. Query, create, update, and delete document data; if the task mentions PostgreSQL / CloudBase PG / app.rdb(), route to postgresql-development instead.
version: 2.36.1
license: MIT
alwaysApply: false
---

## Sibling skills (local only)

Sibling CloudBase skills ship beside this skill. Use local relative paths such as `../auth-tool-cloudbase/SKILL.md`.

If a referenced sibling skill file is missing from this environment, ask the user to install the full CloudBase plugin (or the missing skill). Do **not** HTTP-fetch remote skill or protocol markdown into the agent context.

# CloudBase Document Database Web SDK

## Activation Contract

### Use this first when

- A browser or Web app must read or write CloudBase document database data through `@cloudbase/js-sdk`.
- The request mentions `app.database()`, `db.collection()`, `.where()`, `.watch()`, pagination, aggregation, or geolocation queries in a Web frontend.

### Read before writing code if

- The task is clearly browser-side, but you still need to decide between Web SDK, Mini Program SDK, or backend access.
- The request touches login state, collection permissions, or realtime updates.

### Then also read

- Web login and caller identity -> `../auth-web-cloudbase/SKILL.md`
- General Web app structure -> `../web-development/SKILL.md`
- Mini Program database code -> `../cloudbase-document-database-in-wechat-miniprogram/SKILL.md`

### Do NOT use for

- Mini Program code using `wx.cloud.database()`.
- Server-side or cloud-function database access.
- SQL / MySQL database operations.
- Pure resource-permission administration with no browser SDK code.
- **NEW business tables that the task explicitly asks to put in CloudBase PostgreSQL (CloudBase PG).** Before applying this skill, call `queryEnv(action="info", envId=...)` and read `EnvInfo.RuntimeBackends`. If `postgresql === true` AND the task asks for a new business table to live in PG, switch to the `postgresql-development-cloudbase` skill for that table: it goes through `app.rdb()`, uses PG row-level security (`CREATE POLICY`), and uploads via `app.storage.from('<bucket>').upload('<key>', file)` against an explicitly-created pgstore bucket.
  - Existing NoSQL collections in the same env keep using THIS skill — PG and NoSQL coexist in CloudBase PG environments. The rule is "follow the task / existing surface", not "PG env forbids NoSQL".

### SDK Code vs MCP Tools

**When to write SDK code (use this skill):**
- The task explicitly asks to "modify code" or "use SDK"
- The task asks to implement app/frontend logic
- The task mentions specific SDK methods like `db.collection().add()`, `.get()`, `.update()`
- The context shows an existing Web project with SDK initialization (e.g., `index.js` already has `cloudbase.init()`)

**When to use MCP tools instead:**
- The task asks to manage CloudBase resources (create collection, set permissions, etc.)
- The task involves admin/management operations without writing app code
- The task mentions tools like `writeNoSqlDatabaseContent`, `managePermissions`, etc.

**Key distinction:** If the user says "使用 JS SDK 执行 XX 操作" (use JS SDK to perform XX operation) or "修改代码" (modify code), write SDK code in the project files. Do not use MCP database write tools for app-level data operations.

### Common mistakes / gotchas

- Querying before the user is signed in when the collection rules require identity.
- Using `wx.cloud.database()` or Node SDK patterns in browser code.
- Initializing CloudBase lazily with dynamic imports instead of a shared synchronous app instance.
- Treating security rules as result filters rather than request validators.
- **Expecting a `CUSTOM` security rule to take effect immediately after you call `managePermissions(updateResourcePermission)`.** The backend caches rule evaluators for **2–5 minutes**; first writes after a rule change may silently fail or be rejected with `DATABASE_PERMISSION_DENIED` even when the expression is correct. Either (a) wait a few minutes and retry the same write before assuming the rule is wrong, or (b) verify the rule is live by reading `result.code` / `result.message` on every write and by doing a `get()` round-trip on the just-written `_id`; do not treat a resolved promise as success. See `security-rules.md` → "Propagation And Verification" for the full pattern.
- Misreading the return shape of `db.collection(...).add(...)`. In the CloudBase Web SDK, the created document ID is exposed at top-level `result._id`, not `result.id`, `result.data.id`, or `result.insertedId`.
- For CMS-style collections that need **app-level admin users** to edit/delete all records while editors can only edit/delete their own records, do not oversimplify the rule to `READONLY`. A validated pattern is a `CUSTOM` rule that reads role from `user_roles` by `auth.uid` and combines it with `doc.authorId == auth.uid`, while frontend writes can stay on `.doc(id).update()` / `.doc(id).remove()`.
- Forgetting pagination or indexes for larger collections.

### Minimal checklist

- Confirm this is browser-side document database work.
- Initialize CloudBase once and reuse the same `app` / `db` instance.
- Verify auth expectations before CRUD.
- Read the right companion reference file for the specific operation.

## Overview

This skill covers **browser-side document database usage** via `@cloudbase/js-sdk`.

Use it for:

- CRUD in a Web app
- complex queries and pagination
- aggregation
- realtime listeners with `watch()`
- geolocation queries

## Canonical initialization

```javascript
import cloudbase from "@cloudbase/js-sdk";

const app = cloudbase.init({
  env: "your-env-id"
});

const db = app.database();
const _ = db.command;
```

Important rules:

- Sign in before querying if the collection rules require identity.
- Keep a single shared app/database instance.
- Do not hide initialization inside ad-hoc async loaders unless the framework truly requires it.

## Quick routing

- CRUD -> `./crud-operations.md`
- Complex queries -> `./complex-queries.md`
- Pagination -> `./pagination.md`
- Aggregation -> `./aggregation.md`
- Realtime listeners -> `./realtime.md`
- Geolocation -> `./geolocation.md`
- Security rules -> `./security-rules.md`

## Working rules for a coding agent

1. **Start from the auth model**
   - If the page relies on logged-in user identity, read the Web auth skill before writing database code.

2. **Keep browser code browser-native**
   - Use `app.database()` and collection references.
   - Do not mix in MCP management flows or SQL mental models.

3. **Respect security rules**
   - Collection rules can reject requests before data is read.
   - If the requirement is simple owner-only write access, `READONLY` can be enough.
   - If the requirement is “app-level admin can edit/delete all, editor only own”, use a `CUSTOM` rule. A validated CMS pattern is ``get(`database.user_roles.${auth.uid}`).role == 'admin' || doc.authorId == auth.uid``.
   - For that CMS pattern, frontend writes can stay on `.doc(id).update()` / `.doc(id).remove()`.
   - Reuse whichever role collection already exists and can be addressed by `_id == auth.uid`. In this CMS pattern, `user_roles` keyed by uid is acceptable.
   - A `get()` whose target document is missing fails the request with HTTP 500 — it does not evaluate to `false`, and `||` does not skip it. If the app cannot guarantee a role document per user, keep the role list in one shared document and test ``auth.uid in get(`database.admin_registry.lock`).admins`` instead.
   - If the task fails with permission issues, inspect the rule model rather than assuming the query syntax is wrong.

4. **Return user-friendly errors**
   - Database errors must become readable UI or application errors, not silent failures.
   - For writes, do not treat a resolved promise as success by default. Check write result fields such as `updated` / `deleted` or surfaced `code` / `message`.

5. **Persist IDs from create operations correctly**
   - For Web SDK `.add(...)`, the newly created document ID is `result._id`.
   - Do not look for the ID under `result.id`, `result.data`, or other driver-specific fields.

## Quick examples

### Simple query

```javascript
const result = await db.collection("todos")
  .where({ completed: false })
  .get();
```

### Create and capture document ID

```javascript
const result = await db.collection("posts").add({
  title: "New article",
  content: "...",
  createdAt: new Date()
});

const articleId = result._id;
```

### Ordered pagination

```javascript
const result = await db.collection("posts")
  .orderBy("createdAt", "desc")
  .skip(20)
  .limit(10)
  .get();
```

### Field selection

```javascript
const result = await db.collection("users")
  .field({ name: true, email: true, _id: false })
  .get();
```

## Best practices

1. Define collection-level types or model wrappers in the app code.
2. Use meaningful collection naming conventions.
3. Select only required fields.
4. Add indexes for frequent filters or sort keys.
5. Pair frontend CRUD with explicit permission design.
6. Use pagination instead of unbounded reads.

## Error handling

```javascript
try {
  const result = await db.collection("todos").get();
  console.log(result.data);
} catch (error) {
  console.error("Database error:", error);
}
```

When the SDK returns an operation result, check error indicators and translate them into readable application behavior.

© TencentCloudBase · MIT · TencentCloudBase/skills

Similar skills

All skills for Data and databases →

From the same set20

ai-model-nodejs A skill that teaches the agent to call AI models from a Node.js backend through @cloudbase/node-sdk: text, images, cloud functions, CloudRun. CX Codex +1 998installs cloudrun-development Backend development rules for CloudBase Run: deploying services with long connections, VPC database access, and diagnosing container deploy failures. CX Codex +1 983installs http-api-cloudbase Guides coding agents through direct HTTP calls to Tencent CloudBase platform services. Useful for Python or Go backends, mobile apps, and scripts without official SDKs. CX Codex +1 977installs auth-nodejs-cloudbase A skill for configuring server-side identity, user lookup, and custom login tickets in CloudBase backend services with the Node.js SDK. CX Codex +1 960installs relational-database-mcp-cloudbase A skill that tells an agent how to run SQL, change schema and edit permissions on CloudBase Relational Database through MCP. Marked deprecated. CX Codex +1 956installs auth-web-cloudbase Guides frontend authentication and session handling for Tencent CloudBase in Web apps. Helps agents avoid deprecated methods and broken route guards. CX Codex +1 951installs ai-model-web Directs frontend apps to run AI models via @cloudbase/js-sdk straight from the browser without setting up a Node.js proxy. CX Codex +1 913installs relational-database-web-cloudbase Sets the init pattern for @cloudbase/js-sdk in the browser so you get one shared CloudBase relational DB client and Supabase-style queries. CX Codex +1 899installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor