cloudbase-document-database-web-sdk
Scannednpx machina-cli add skill Microck/ordinary-claude-skills/cloudbase-document-database-web-sdk --openclawCloudBase Document Database Web SDK
This skill provides guidance on using the CloudBase document database Web SDK for data operations in web applications.
Core Concepts
Initialization
Before using any database operations, initialize the CloudBase SDK:
import cloudbase from "@cloudbase/js-sdk";
// UMD version
// If you are not using npm, And want to use UMD version instead. You should refer to https://docs.cloudbase.net/quick-start/#web-%E5%BF%AB%E9%80%9F%E4%BD%93%E9%AA%8C for latest version of UMD version.
const app = cloudbase.init({
env: "your-env-id", // Replace with your environment id
});
const db = app.database();
const _ = db.command; // Get query operators
// ... login
Initialization rules (Web, @cloudbase/js-sdk):
- Always use synchronous initialization with the pattern above
- Do not lazy-load the SDK with
import("@cloudbase/js-sdk") - Do not wrap SDK initialization in async helpers such as
initCloudBase()with internalinitPromisecaches
Remember to sign in(auth) is *REQUIRED before actually querying the database.
Collection Reference
Access collections using:
db.collection('collection-name')
Query Operators
CloudBase provides query operators via db.command (aliased as _):
_.gt(value)- Greater than_.gte(value)- Greater than or equal_.lt(value)- Less than_.lte(value)- Less than or equal_.eq(value)- Equal to_.neq(value)- Not equal to_.in(array)- Value in array_.nin(array)- Value not in array
Basic Operations
Query Single Document
Query by document ID:
const result = await db.collection('todos')
.doc('docId')
.get();
Query Multiple Documents
Query with conditions:
const result = await db.collection('todos')
.where({
completed: false,
priority: 'high'
})
.get();
Note: get() returns 100 records by default, maximum 1000.
Query Methods Chaining
Combine methods for complex queries:
.where(conditions)- Filter conditions.orderBy(field, direction)- Sort by field ('asc' or 'desc').limit(number)- Limit results (default 100, max 1000).skip(number)- Skip records for pagination.field(object)- Specify fields to return (true/false)
Advanced Features
For detailed information on specific topics, refer to:
CRUD Operations
See ./crud-operations.md for:
- Creating documents (add, batch add)
- Updating documents (partial updates, operators)
- Deleting documents (conditional delete, soft delete)
- Complete CRUD manager examples
Complex Queries
See ./complex-queries.md for:
- Using query operators
- Combining multiple conditions
- Field selection
- Sorting and limiting results
Pagination
See ./pagination.md for:
- Implementing page-based navigation
- Calculating skip and limit values
- Cursor-based pagination
- Infinite scroll patterns
Aggregation Queries
See ./aggregation.md for:
- Grouping data
- Statistical calculations
- Pipeline operations
- Time-based aggregations
Geolocation Queries
See ./geolocation.md for:
- Proximity searches
- Area-based queries
- Geographic indexing requirements
- Distance-based features
Security Rules
See ./security-rules.md for:
- Configuring database permissions
- Simple permissions vs custom rules
- Permission categories and usage
- Security rule syntax and examples
Common Patterns
Error Handling
Always wrap database operations in try-catch:
try {
const result = await db.collection('todos').get();
console.log(result.data);
} catch (error) {
console.error('Database error:', error);
}
Return Value Structure
Database operations return:
{
data: [...], // Array of documents
// Additional metadata
}
Important Notes
- Environment ID: Replace
"your-env-id"with actual CloudBase environment ID - Default Limits:
get()returns 100 records by default - Collection Names: Use string literals for collection names
- Geolocation Index: Geographic queries require proper indexing
- Async/Await: All database operations are asynchronous
Best Practices
- Initialize SDK once at application startup
- Reuse database instance across the application
- Use query operators for complex conditions
- Implement pagination for large datasets
- Select only needed fields to reduce data transfer
- Handle errors appropriately
- Create indexes for frequently queried fields
Quick Reference
Common query examples:
// Simple query
db.collection('todos').where({ status: 'active' }).get()
// With operators
db.collection('users').where({ age: _.gt(18) }).get()
// Pagination
db.collection('posts')
.orderBy('createdAt', 'desc')
.skip(20)
.limit(10)
.get()
// Field selection
db.collection('users')
.field({ name: true, email: true, _id: false })
.get()
For more detailed examples and advanced usage patterns, refer to the companion reference files in this directory.
Source
git clone https://github.com/Microck/ordinary-claude-skills/blob/main/skills_all/cloudbase-document-database-web-sdk/SKILL.mdView on GitHub Overview
This skill shows how to use the CloudBase document database Web SDK for creating, querying, updating, and deleting data in web apps. It covers initialization, collection access, query operators, basic CRUD, and advanced features like pagination and geolocation queries.
How This Skill Works
Initialize with cloudbase.init and obtain db = app.database(), then access collections via db.collection('name'). Use db.command as _. to build query operators. Chain methods like where, orderBy, limit, skip, and field to shape results; ensure authentication before querying and handle errors with try-catch.
When to Use It
- When you need to query a single document by ID or fetch multiple documents with filters
- When you require sorting, limiting, or skipping results for pagination
- When performing complex queries with multiple conditions and field projections
- When implementing pagination, infinite scroll, or cursor-based navigation
- When needing geolocation-based proximity or area-based queries with proper indexing
Quick Start
- Step 1: Initialize the SDK and create a db reference (sync): const app = cloudbase.init({ env: 'your-env-id' }); const db = app.database();
- Step 2: Get a collection reference: const todos = db.collection('todos');
- Step 3: Run a basic query or CRUD operation, e.g., const result = await todos.where({ completed: false }).get();
Best Practices
- Always initialize synchronously with the provided pattern and avoid lazy-loading
- Sign in/authenticate before executing any queries
- Use the collection reference via db.collection('collection-name') for operations
- Leverage db.command (aliased as _) for query operators like gt, lt, in, nin, etc.
- Wrap operations in try-catch and manage default pagination (100/1000 limits)
Example Use Cases
- Query a single document by ID: const result = await db.collection('todos').doc('docId').get();
- Fetch multiple docs with filters: const result = await db.collection('todos').where({ completed: false, priority: 'high' }).get();
- Chain for complex queries with sort and limit: db.collection('todos').where(...).orderBy('createdAt', 'desc').limit(50).get();
- Paginate results using skip for rapid navigation: db.collection('todos').where(...).limit(100).skip(200).get();
- Return only specific fields: db.collection('todos').where(...).field({ title: true, dueDate: true }).get();