cloudbase-document-database-web-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

CloudBase Document Database Web SDK

CloudBase文档数据库Web SDK

This skill provides guidance on using the CloudBase document database Web SDK for data operations in web applications.
本技能为在Web应用中使用CloudBase文档数据库Web SDK进行数据操作提供指导。

Core Concepts

核心概念

Initialization

初始化

Before using any database operations, initialize the CloudBase SDK:
javascript
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
Remember to sign in(auth) is *REQUIRED before actually querying the database.
在执行任何数据库操作之前,需要先初始化CloudBase SDK:
javascript
import cloudbase from "@cloudbase/js-sdk";
// UMD版本
// 如果你不使用npm,而是想使用UMD版本,请参考https://docs.cloudbase.net/quick-start/#web-%E5%BF%AB%E9%80%9F%E4%BD%93%E9%AA%8C获取最新的UMD版本。

const app = cloudbase.init({
  env: "your-env-id", // 替换为你的环境ID
});


const db = app.database();
const _ = db.command; // 获取查询操作符

// ... 登录
注意:在实际查询数据库之前,必须完成登录(认证)操作。

Collection Reference

集合引用

Access collections using:
javascript
db.collection('collection-name')
通过以下方式访问集合:
javascript
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
CloudBase通过
db.command
(别名
_
)提供查询操作符:
  • _.gt(value)
    - 大于
  • _.gte(value)
    - 大于等于
  • _.lt(value)
    - 小于
  • _.lte(value)
    - 小于等于
  • _.eq(value)
    - 等于
  • _.neq(value)
    - 不等于
  • _.in(array)
    - 值在数组中
  • _.nin(array)
    - 值不在数组中

Basic Operations

基础操作

Query Single Document

查询单个文档

Query by document ID:
javascript
const result = await db.collection('todos')
    .doc('docId')
    .get();
通过文档ID查询:
javascript
const result = await db.collection('todos')
    .doc('docId')
    .get();

Query Multiple Documents

查询多个文档

Query with conditions:
javascript
const result = await db.collection('todos')
    .where({
        completed: false,
        priority: 'high'
    })
    .get();
Note:
get()
returns 100 records by default, maximum 1000.
带条件查询:
javascript
const result = await db.collection('todos')
    .where({
        completed: false,
        priority: 'high'
    })
    .get();
注意:
get()
默认返回100条记录,最多可返回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)
组合方法实现复杂查询:
  • .where(conditions)
    - 过滤条件
  • .orderBy(field, direction)
    - 按字段排序('asc' 或 'desc')
  • .limit(number)
    - 限制结果数量(默认100,最大1000)
  • .skip(number)
    - 跳过指定数量的记录以实现分页
  • .field(object)
    - 指定要返回的字段(true/false)

Advanced Features

高级功能

For detailed information on specific topics, refer to:
如需特定主题的详细信息,请参考:

CRUD Operations

CRUD操作

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
查看
./crud-operations.md
获取以下内容:
  • 创建文档(新增、批量新增)
  • 更新文档(部分更新、操作符使用)
  • 删除文档(条件删除、软删除)
  • 完整的CRUD管理器示例

Complex Queries

复杂查询

See
./complex-queries.md
for:
  • Using query operators
  • Combining multiple conditions
  • Field selection
  • Sorting and limiting results
查看
./complex-queries.md
获取以下内容:
  • 查询操作符的使用
  • 多条件组合
  • 字段选择
  • 排序与结果限制

Pagination

分页

See
./pagination.md
for:
  • Implementing page-based navigation
  • Calculating skip and limit values
  • Cursor-based pagination
  • Infinite scroll patterns
查看
./pagination.md
获取以下内容:
  • 实现基于页码的导航
  • 计算skip和limit值
  • 基于游标分页
  • 无限滚动模式

Aggregation Queries

聚合查询

See
./aggregation.md
for:
  • Grouping data
  • Statistical calculations
  • Pipeline operations
  • Time-based aggregations
查看
./aggregation.md
获取以下内容:
  • 数据分组
  • 统计计算
  • 管道操作
  • 基于时间的聚合

Geolocation Queries

地理位置查询

See
./geolocation.md
for:
  • Proximity searches
  • Area-based queries
  • Geographic indexing requirements
  • Distance-based features
查看
./geolocation.md
获取以下内容:
  • 邻近搜索
  • 基于区域的查询
  • 地理索引要求
  • 基于距离的功能

Realtime Database

实时数据库

See
./realtime.md
for:
  • Real-time data synchronization using watch() method
  • Setting up listeners for document changes
  • Handling real-time updates in chat and collaboration apps
  • Performance optimization and error handling
  • Common patterns for real-time applications
查看
./realtime.md
获取以下内容:
  • 使用watch()方法实现实时数据同步
  • 设置文档变更监听器
  • 在聊天和协作应用中处理实时更新
  • 性能优化与错误处理
  • 实时应用的常见模式

Security Rules

安全规则

See
./security-rules.md
for:
  • Configuring database permissions
  • Simple permissions vs custom rules
  • Permission categories and usage
  • Security rule syntax and examples
查看
./security-rules.md
获取以下内容:
  • 配置数据库权限
  • 简单权限与自定义规则对比
  • 权限分类与使用场景
  • 安全规则语法与示例

Common Patterns

常见模式

Error Handling

错误处理

Always wrap database operations in try-catch:
javascript
try {
    const result = await db.collection('todos').get();
    console.log(result.data);
} catch (error) {
    console.error('Database error:', error);
}
始终将数据库操作包裹在try-catch中:
javascript
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:
javascript
{
    data: [...], // Array of documents
    // Additional metadata
}
数据库操作返回以下结构:
javascript
{
    data: [...], // 文档数组
    // 其他元数据
}

Important Notes

重要注意事项

  1. Environment ID: Replace
    "your-env-id"
    with actual CloudBase environment ID
  2. Default Limits:
    get()
    returns 100 records by default
  3. Collection Names: Use string literals for collection names
  4. Geolocation Index: Geographic queries require proper indexing
  5. Async/Await: All database operations are asynchronous
  1. 环境ID:将
    "your-env-id"
    替换为实际的CloudBase环境ID
  2. 默认限制
    get()
    默认返回100条记录
  3. 集合名称:使用字符串字面量作为集合名称
  4. 地理索引:地理位置查询需要正确配置索引
  5. Async/Await:所有数据库操作均为异步操作

Best Practices

最佳实践

  1. Initialize SDK once at application startup
  2. Reuse database instance across the application
  3. Use query operators for complex conditions
  4. Implement pagination for large datasets
  5. Select only needed fields to reduce data transfer
  6. Handle errors appropriately
  7. Create indexes for frequently queried fields
  1. 在应用启动时仅初始化一次SDK
  2. 在整个应用中复用数据库实例
  3. 使用查询操作符实现复杂条件
  4. 为大型数据集实现分页
  5. 仅选择需要的字段以减少数据传输
  6. 妥善处理错误
  7. 为频繁查询的字段创建索引

Coding Rules

编码规范

  • It is HIGHLY RECOMMENDED to have a type definition and model layer for each collection in your document database. This will help you to avoid errors and make your code more robust. That would be the single source of truth for your database schema. Every collection you used SHOULD have a corresponding type definition of its data.
  • Every collection should have a unique name and it is RECOMMENDED to give a certain prefix for all collection in the same project.
  • Collections should have well defined and meaningful security rules(policy) for create, read, write and delete permission according to the business logic. Details refer to
    ./security-rules.md
    . When writing expressions in security rules, The type definition of the collection mention above can be used as the type reference.
  • 强烈建议为文档数据库中的每个集合添加类型定义和模型层。这将帮助你避免错误并让代码更健壮,同时作为数据库 schema 的唯一可信来源。每个使用的集合都必须有对应的数据类型定义。
  • 每个集合都应有唯一的名称,建议为同一项目中的所有集合添加统一前缀。
  • 应根据业务逻辑为集合定义清晰且有意义的安全规则(策略),涵盖创建、读取、写入和删除权限。详情请参考
    ./security-rules.md
    。在编写安全规则表达式时,上述集合的类型定义可作为类型参考。

Quick Reference

快速参考

Common query examples:
javascript
// 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.
常见查询示例:
javascript
// 简单查询
db.collection('todos').where({ status: 'active' }).get()

// 使用操作符
db.collection('users').where({ age: _.gt(18) }).get()

// 分页
db.collection('posts')
    .orderBy('createdAt', 'desc')
    .skip(20)
    .limit(10)
    .get()

// 字段选择
db.collection('users')
    .field({ name: true, email: true, _id: false })
    .get()
如需更详细的示例和高级使用模式,请参考本目录中的配套参考文件。

Error handling

错误处理

EVERY database operation(including
get()
,
add()
,
update()
,
delete()
etc)should check the return value's code for any errors. For example:
javascript
const result = await db.collection('todos').add(newTodo);
if(typeof result.code === 'string') {
    // Handle error ...
}
Error MUST be handled with detail and human-readable message and friendly UI.
所有数据库操作(包括
get()
add()
update()
delete()
等)都应检查返回值的code字段以判断是否存在错误。例如:
javascript
const result = await db.collection('todos').add(newTodo);
if(typeof result.code === 'string') {
    // 处理错误 ...
}
错误必须以详细、易读的信息和友好的UI进行处理。