Standalone Install Note
If this environment only installed the current skill, start from the CloudBase main entry and use the published cloudbase/references/... paths for sibling skills.
- CloudBase main entry:
https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/SKILL.md
- Current skill raw source:
https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/no-sql-web-sdk/SKILL.md
Keep local references/... paths for files that ship with the current skill directory. When this file points to a sibling skill such as auth-tool or web-development, use the standalone fallback URL shown next to that reference.
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/SKILL.md (standalone fallback: https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/auth-web/SKILL.md)
- General Web app structure ->
../web-development/SKILL.md (standalone fallback: https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/web-development/SKILL.md)
- Mini Program database code ->
../no-sql-wx-mp-sdk/SKILL.md (standalone fallback: https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/no-sql-wx-mp-sdk/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
envQuery(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 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
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
Start from the auth model
- If the page relies on logged-in user identity, read the Web auth skill before writing database code.
Keep browser code browser-native
- Use
app.database() and collection references.
- Do not mix in MCP management flows or SQL mental models.
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.
- If the task fails with permission issues, inspect the rule model rather than assuming the query syntax is wrong.
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.
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
const result = await db.collection("todos")
.where({ completed: false })
.get();
Create and capture document ID
const result = await db.collection("posts").add({
title: "New article",
content: "...",
createdAt: new Date()
});
const articleId = result._id;
Ordered pagination
const result = await db.collection("posts")
.orderBy("createdAt", "desc")
.skip(20)
.limit(10)
.get();
Field selection
const result = await db.collection("users")
.field({ name: true, email: true, _id: false })
.get();
Best practices
- Define collection-level types or model wrappers in the app code.
- Use meaningful collection naming conventions.
- Select only required fields.
- Add indexes for frequent filters or sort keys.
- Pair frontend CRUD with explicit permission design.
- Use pagination instead of unbounded reads.
Error handling
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.
1---
2name: cloudbase-document-database-web-sdk
3description: 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.
4version: 2.23.8
5alwaysApply: false
6---
7
8## Standalone Install Note
9
10If this environment only installed the current skill, start from the CloudBase main entry and use the published `cloudbase/references/...` paths for sibling skills.
11
12- CloudBase main entry: `https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/SKILL.md`
13- Current skill raw source: `https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/no-sql-web-sdk/SKILL.md`
14
15Keep local `references/...` paths for files that ship with the current skill directory. When this file points to a sibling skill such as `auth-tool` or `web-development`, use the standalone fallback URL shown next to that reference.
16
17# CloudBase Document Database Web SDK
18
19## Activation Contract
20
21### Use this first when
22
23- A browser or Web app must read or write CloudBase document database data through `@cloudbase/js-sdk`.
24- The request mentions `app.database()`, `db.collection()`, `.where()`, `.watch()`, pagination, aggregation, or geolocation queries in a Web frontend.
25
26### Read before writing code if
27
28- The task is clearly browser-side, but you still need to decide between Web SDK, Mini Program SDK, or backend access.
29- The request touches login state, collection permissions, or realtime updates.
30
31### Then also read
32
33- Web login and caller identity -> `../auth-web/SKILL.md` (standalone fallback: `https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/auth-web/SKILL.md`)
34- General Web app structure -> `../web-development/SKILL.md` (standalone fallback: `https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/web-development/SKILL.md`)
35- Mini Program database code -> `../no-sql-wx-mp-sdk/SKILL.md` (standalone fallback: `https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/no-sql-wx-mp-sdk/SKILL.md`)
36
37### Do NOT use for
38
39- Mini Program code using `wx.cloud.database()`.
40- Server-side or cloud-function database access.
41- SQL / MySQL database operations.
42- Pure resource-permission administration with no browser SDK code.
43- **NEW business tables that the task explicitly asks to put in CloudBase PostgreSQL (CloudBase PG).** Before applying this skill, call `envQuery(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` 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.
44 - 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".
45
46### SDK Code vs MCP Tools
47
48**When to write SDK code (use this skill):**
49- The task explicitly asks to "modify code" or "use SDK"
50- The task asks to implement app/frontend logic
51- The task mentions specific SDK methods like `db.collection().add()`, `.get()`, `.update()`
52- The context shows an existing Web project with SDK initialization (e.g., `index.js` already has `cloudbase.init()`)
53
54**When to use MCP tools instead:**
55- The task asks to manage CloudBase resources (create collection, set permissions, etc.)
56- The task involves admin/management operations without writing app code
57- The task mentions tools like `writeNoSqlDatabaseContent`, `managePermissions`, etc.
58
59**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.
60
61### Common mistakes / gotchas
62
63- Querying before the user is signed in when the collection rules require identity.
64- Using `wx.cloud.database()` or Node SDK patterns in browser code.
65- Initializing CloudBase lazily with dynamic imports instead of a shared synchronous app instance.
66- Treating security rules as result filters rather than request validators.
67- **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.
68- 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`.
69- 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()`.
70- Forgetting pagination or indexes for larger collections.
71
72### Minimal checklist
73
74- Confirm this is browser-side document database work.
75- Initialize CloudBase once and reuse the same `app` / `db` instance.
76- Verify auth expectations before CRUD.
77- Read the right companion reference file for the specific operation.
78
79## Overview
80
81This skill covers **browser-side document database usage** via `@cloudbase/js-sdk`.
82
83Use it for:
84
85- CRUD in a Web app
86- complex queries and pagination
87- aggregation
88- realtime listeners with `watch()`
89- geolocation queries
90
91## Canonical initialization
92
93```javascript
94import cloudbase from "@cloudbase/js-sdk";
95
96const app = cloudbase.init({
97 env: "your-env-id"
98});
99
100const db = app.database();
101const _ = db.command;
102```
103
104Important rules:
105
106- Sign in before querying if the collection rules require identity.
107- Keep a single shared app/database instance.
108- Do not hide initialization inside ad-hoc async loaders unless the framework truly requires it.
109
110## Quick routing
111
112- CRUD -> `./crud-operations.md`
113- Complex queries -> `./complex-queries.md`
114- Pagination -> `./pagination.md`
115- Aggregation -> `./aggregation.md`
116- Realtime listeners -> `./realtime.md`
117- Geolocation -> `./geolocation.md`
118- Security rules -> `./security-rules.md`
119
120## Working rules for a coding agent
121
1221. **Start from the auth model**
123 - If the page relies on logged-in user identity, read the Web auth skill before writing database code.
124
1252. **Keep browser code browser-native**
126 - Use `app.database()` and collection references.
127 - Do not mix in MCP management flows or SQL mental models.
128
1293. **Respect security rules**
130 - Collection rules can reject requests before data is read.
131 - If the requirement is simple owner-only write access, `READONLY` can be enough.
132 - 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`.
133 - For that CMS pattern, frontend writes can stay on `.doc(id).update()` / `.doc(id).remove()`.
134 - 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.
135 - If the task fails with permission issues, inspect the rule model rather than assuming the query syntax is wrong.
136
1374. **Return user-friendly errors**
138 - Database errors must become readable UI or application errors, not silent failures.
139 - For writes, do not treat a resolved promise as success by default. Check write result fields such as `updated` / `deleted` or surfaced `code` / `message`.
140
1415. **Persist IDs from create operations correctly**
142 - For Web SDK `.add(...)`, the newly created document ID is `result._id`.
143 - Do not look for the ID under `result.id`, `result.data`, or other driver-specific fields.
144
145## Quick examples
146
147### Simple query
148
149```javascript
150const result = await db.collection("todos")
151 .where({ completed: false })
152 .get();
153```
154
155### Create and capture document ID
156
157```javascript
158const result = await db.collection("posts").add({
159 title: "New article",
160 content: "...",
161 createdAt: new Date()
162});
163
164const articleId = result._id;
165```
166
167### Ordered pagination
168
169```javascript
170const result = await db.collection("posts")
171 .orderBy("createdAt", "desc")
172 .skip(20)
173 .limit(10)
174 .get();
175```
176
177### Field selection
178
179```javascript
180const result = await db.collection("users")
181 .field({ name: true, email: true, _id: false })
182 .get();
183```
184
185## Best practices
186
1871. Define collection-level types or model wrappers in the app code.
1882. Use meaningful collection naming conventions.
1893. Select only required fields.
1904. Add indexes for frequent filters or sort keys.
1915. Pair frontend CRUD with explicit permission design.
1926. Use pagination instead of unbounded reads.
193
194## Error handling
195
196```javascript
197try {
198 const result = await db.collection("todos").get();
199 console.log(result.data);
200} catch (error) {
201 console.error("Database error:", error);
202}
203```
204
205When the SDK returns an operation result, check error indicators and translate them into readable application behavior.