增删改查
初始化 SDK
import cloudbase from "@cloudbase/js-sdk";
const app = cloudbase.init({
env: "your-env-id",
});
const db = app.database();
const _ = db.command; // 获取查询指令
新增数据
单条新增
向集合中添加一条新记录。
参数说明
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| data | object | 是 | 要新增的数据对象 |
代码示例
// 添加单条记录
const result = await db.collection('todos').add({
title: '学习 CloudBase',
content: '完成数据库操作教程',
completed: false,
priority: 'high',
createdAt: new Date(),
tags: ['学习', '技术']
})
console.log('新增成功,文档 ID:', result._id)
地理位置新增
// 创建地理位置点
const point = new db.Geo.Point(longitude, latitude);
// 创建地理路径
const line = new db.Geo.LineString([
new db.Geo.Point(lngA, latA),
new db.Geo.Point(lngB, latB)
]);
// 创建地理区域
const polygon = new db.Geo.Polygon([
new db.Geo.LineString([
new db.Geo.Point(lngA, latA),
new db.Geo.Point(lngB, latB),
new db.Geo.Point(lngC, latC),
new db.Geo.Point(lngA, latA) // 闭合
])
]);
const result = await db.collection('todos').add({
location: point,
path: line,
area: polygon
})
查询数据
单条查询
通过文档 ID 查询指定记录。
参数说明
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| docId | string | 是 | 文档的唯一标识符 |
代码示例
// 根据文档 ID 查询单条记录
const result = await db.collection('todos')
.doc('docId')
.get()
返回结果
{
data: [{
_id: "todo-id-123",
title: "学习 CloudBase",
completed: false,
// ... 其他字段
}],
}
多条查询
查询集合中的多条记录,支持条件筛选、排序、分页等。
⚠️ 注意:
get()方法默认返回100条数据,如需更多数据请使用分页
参数说明
| 方法 | 参数类型 | 必填 | 说明 |
|---|---|---|---|
| where() | object | 否 | 查询条件,支持操作符 |
| orderBy() | string, string | 否 | 排序字段和方向('asc' 或 'desc') |
| limit() | number | 否 | 限制返回记录数,默认 100 条,最多返回 1000 条 |
| skip() | number | 否 | 跳过记录数,用于分页 |
| field() | object | 否 | 指定返回字段,true 表示返回,false 表示不返回 |
// 查询所有记录
const result = await db.collection('todos').get()
// 条件查询
const result = await db.collection('todos')
.where({
completed: false,
priority: 'high'
})
.get()
复杂查询
const _ = db.command
// 复杂条件查询
const result = await db.collection('todos')
.where({
// 年龄大于 18
age: _.gt(18),
// 标签包含 '技术'
tags: _.in(['技术', '学习']),
// 创建时间在最近一周内
createdAt: _.gte(new Date(Date.now() - 7 * 24 * 60 * 60 * 1000))
})
.orderBy('createdAt', 'desc') // 按创建时间倒序
.limit(10) // 限制 10 条
.skip(0) // 跳过 0 条(分页)
.field({ // 只返回指定字段
title: true,
completed: true,
createdAt: true
})
.get()
分页查询
// 分页查询示例
const pageSize = 10
const pageNum = 1
const result = await db.collection('todos')
.orderBy('createdAt', 'desc')
.skip((pageNum - 1) * pageSize)
.limit(pageSize)
.get()
聚合查询
聚合语法具体参考 聚合查询
// 统计查询
const result = await db.collection('todos')
.aggregate()
.group({
_id: '$priority',
count: {
$sum: 1
}
})
.end()
console.log('按优先级统计:', result.list)
地理位置查询
⚠️ 注意:对地理位置字段进行查询时,请建立地理位置索引,否则查询将失败
const _ = db.command
// 查询附近的用户(按距离排序)
db.collection("users").where({
location: _.geoNear({
geometry: new db.Geo.Point(116.404, 39.915), // 天安门坐标
maxDistance: 1000, // 最大距离1000米
minDistance: 0 // 最小距离0米
})
}).get()
// 查询指定区域内的用户
db.collection("users").where({
location: _.geoWithin({
geometry: polygon // 使用上面定义的多边形
})
}).get()
// 查询与路径相交的用户
db.collection("users").where({
location: _.geoIntersects({
geometry: line // 使用上面定义的路径
})
}).get()
更新数据
单条更新
通过文档 ID 更新指定记录。
参数说明
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| docId | string | 是 | 要更新的文档 ID |
| data | object | 是 | 要更新的数据对象 |
代码示例
// 更新指定文档
const result = await db.collection('todos')
.doc('todo-id')
.update({
title: '学习 CloudBase 数据库',
completed: true,
updatedAt: new Date(),
completedBy: 'user123'
})
批量更新
根据查询条件批量更新多条记录。
参数说明
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| where | object | 是 | 查询条件,确定要更新的记录 |
| data | object | 是 | 要更新的数据对象 |
代码示例
// 批量更新多条记录
const batchResult = await db.collection('todos')
.where({
completed: false,
priority: 'low'
})
.update({
priority: 'normal',
updatedAt: new Date()
})
更新或创建
更新文档,如果不存在则创建:
const setResult = await db.collection('todos')
.doc("doc-id")
.set({
completed: false,
priority: 'low'
})
删除数据
单条删除
通过文档 ID 删除指定记录。
参数说明
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| docId | string | 是 | 要删除的文档 ID |
代码示例
// 删除指定文档
const result = await db.collection('todos')
.doc('todo-id')
.remove()
批量删除
根据查询条件批量删除多条记录。
参数说明
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| where | object | 是 | 查询条件,确定要删除的记录 |
代码示例
// 批量删除多条记录
const _ = db.command
const batchResult = await db.collection('todos')
.where({
completed: true,
createdAt: _.lt(new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)) // 30天前
})
.remove()
文档支持的操作方法
| 方法 | 说明 | 示例 |
|---|---|---|
add() | 新增文档 | doc.add(data) |
get() | 查询文档 | doc.get() |
update() | 更新文档 | doc.update(data) |
set() | 设置文档(不存在则创建) | doc.set(data) |
remove() | 删除文档 | doc.remove() |
count() | 统计数量 | doc.count() |
where() | 查询条件 | doc.where(condition) |
orderBy() | 排序 | doc.orderBy(field, order) |
limit() | 限制数量 | doc.limit(num) |
skip() | 跳过数量 | doc.skip(num) |
field() | 指定字段 | doc.field(fields) |
doc() | 获取文档引用 | doc.doc(id) |
watch() | 实时监听 | doc.watch(options) |