概述
Database API 提供了一套完整的文档数据库操作功能,支持数据的增删改查、复杂查询、聚合操作、地理位置查询和事务操作。
提示
v3.3 及以上版本在调用相关 API 时,使用的是 HTTP API 的开放能力。
Database API 按照功能用途分为以下类别:
- 初始化:获取数据库实例
- 集合方法:获取集合引用和创建集合
- 文档方法:获取文档引用
- 新增数据:向集合中添加单条或多条数据记录
- 查询数据:支持单条查询、条件查询、分页查询、聚合查询和地理位置查询
- 更新数据:支持单条更新、批量更新和更新或创建操作
- 删除数据:支持单条删除和批量删除操作
- 操作符:查询操作符和更新操作符
- 事务操作:支持事务的开启、提交和回滚
- 实时监听:支持对文档或查询结果的实时变化监听
- 高级操作:执行 MongoDB 原生命令
基础使用示例
- 初始化配置
- 新增数据
- 查询数据
- 更新数据
- 删除数据
- 批量操作
- 分页查询
- 聚合统计
- 实时监听
- 错误处理
Publishable Key 可前往 云开发平台/API Key 配置 中生成
import cloudbase from "@cloudbase/js-sdk";
// 初始化
const app = cloudbase.init({
env: "your-env-id", // 替换为您的环境ID
region: "ap-shanghai", // 地域,默认为上海
accessKey: "", // 填入生成的 Publishable Key
});
// 获取数据库引用
const db = app.database();
// 获取查询指令
const _ = db.command;
// 获取地理位置类型
const Geo = db.Geo;
// 向集合中添加一条新记录
async function addTodo() {
const result = await db.collection("todos").add({
title: "学习 CloudBase",
content: "完成数据库操作教程",
completed: false,
priority: "high",
createdAt: new Date(),
tags: ["学习", "技术"],
});
console.log("新增成功,文档 ID:", result.id);
}
// 指定文档 ID 新增(使用 set)
async function addTodoWithId() {
const result = await db.collection("todos").doc("custom-id").set({
title: "指定ID的任务",
completed: false,
createdAt: new Date(),
});
console.log("新增成功");
}
// 查询集合中的数据
async function queryTodos() {
const _ = db.command;
// 条件查询:未完成的高优先级任务
const result = await db
.collection("todos")
.where({
completed: false,
priority: "high",
})
.orderBy("createdAt", "desc")
.limit(10)
.get();
console.log("查询结果:", result.data);
// 复杂查询:使用操作符
const complexResult = await db
.collection("todos")
.where({
// 优先级为 high 或 medium
priority: _.in(["high", "medium"]),
// 最近7天创建
createdAt: _.gte(new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)),
})
.field({
title: true,
priority: true,
createdAt: true,
})
.get();
console.log("复杂查询结果:", complexResult.data);
}
// 更新指定文档
async function updateTodo(todoId) {
const result = await db.collection("todos").doc(todoId).update({
completed: true,
updatedAt: new Date(),
});
console.log("更新成功 ,影响记录数:", result.updated);
}
// 使用操作符更新
async function updateWithOperators(todoId) {
const _ = db.command;
const result = await db
.collection("todos")
.doc(todoId)
.update({
// 浏览次数 +1
viewCount: _.inc(1),
// 添加新标签(不重复)
tags: _.addToSet("重要"),
// 更新时间
updatedAt: new Date(),
});
console.log("更新成功");
}
// 删除指定文档
async function deleteTodo(todoId) {
const result = await db.collection("todos").doc(todoId).remove();
console.log("删除成功,影响记录数:", result.deleted);
}
// 条件删除
async function deleteCompletedTodos() {
const result = await db
.collection("todos")
.where({
completed: true,
})
.remove();
console.log("删除已完成任务,影响记录数:", result.deleted);
}
// 批量更新:将所有低优先级任务改为普通优先级
async function batchUpdate() {
const result = await db
.collection("todos")
.where({
priority: "low",
})
.update({
priority: "normal",
updatedAt: new Date(),
});
console.log("批量更新成功,影响记录数:", result.updated);
}
// 批量删除:删除30天前已完成的任务
async function batchDelete() {
const _ = db.command;
const result = await db
.collection("todos")
.where({
completed: true,
createdAt: _.lt(new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)),
})
.remove();
console.log("批量删除成功,影响记录数:", result.deleted);
}
// 分页查询示例
async function paginatedQuery(pageNum = 1, pageSize = 10) {
const result = await db
.collection("todos")
.where({
completed: false,
})
.orderBy("createdAt", "desc")
.skip((pageNum - 1) * pageSize)
.limit(pageSize)
.get();
console.log(`第 ${pageNum} 页数据:`, result.data);
console.log("当前页数量:", result.data.length);
return {
data: result.data,
pageNum,
pageSize,
};
}
// 获取总数用于计算总页数
async function getTotalCount() {
const result = await db
.collection("todos")
.where({
completed: false,
})
.count();
console.log("总记录数:", result.total);
return result.total;
}
// 聚合统计示例
async function aggregateStats() {
// 按优先级分组统计数量
const result = await db
.collection("todos")
.aggregate()
.group({
_id: "$priority",
count: { $sum: 1 },
})
.sort({
count: -1,
})
.end();
console.log("按优先级统计:", result.data);
// 输出: [{ _id: 'high', count: 15 }, { _id: 'normal', count: 30 }, ...]
// 统计已完成和未完成数量
const statusResult = await db
.collection("todos")
.aggregate()
.group({
_id: "$completed",
count: { $sum: 1 },
})
.end();
console.log("完成状态统计:", statusResult.data);
}
// 实时监听数据变化
function watchTodos() {
const listener = db
.collection("todos")
.where({
completed: false,
})
.orderBy("createdAt", "desc")
.limit(20)
.watch({
onChange: (snapshot) => {
console.log("数据变化:", snapshot.type);
if (snapshot.type === "init") {
// 初始化数据
console.log("初始数据:", snapshot.docs);
} else {
// 增量变化
snapshot.docChanges.forEach((change) => {
switch (change.dataType) {
case "add":
console.log("新增文档:", change.doc);
break;
case "update":
console.log("更新文档:", change.doc);
break;
case "remove":
console.log("删除文档:", change.docId);
break;
}
});
}
},
onError: (error) => {
console.error("监听错误:", error);
},
});
// 返回监听器,用于后续关闭
return listener;
}
// 使用示例
const listener = watchTodos();
// 在需要时关闭监听
// listener.close();
// 完整的错误处理示例
async function safeDbOperation() {
try {
// 查询操作
const result = await db
.collection("todos")
.where({ completed: false })
.get();
if (result.code) {
switch (result.code) {
case "PERMISSION_DENIED":
console.error("权限不足,请检查安全规则配置");
break;
case "INVALID_PARAM":
console.error("参数错误,请检查查询条件");
break;
case "DATABASE_NOT_FOUND":
console.error("数据库或集合不存在");
break;
case "NETWORK_ERROR":
console.error("网络错误,请检查网络连接");
break;
default:
console.error("未知错误:", result.message);
}
return { success: false, error: result.message };
}
console.log("查询成功:", result.data);
return { success: true, data: result.data };
} catch (error) {
// 其他错误处理
console.error("