增删改查
🔧 SDK 初始化
请参考 SDK 初始化 文档进行 SDK 初始化配置。初始化后拿到对应的数据库实例 db
,即可开始进行数据操作。
查询操作符
数据库 API 提供了大于、小于等多种动态查询指令,这些指令都暴露在 db.command
对象上。
📖 详细文档:wxCloud 数据库操作符
操作符 | 说明 | 示例 |
---|---|---|
eq | 等于 | {age: _.eq(18)} |
neq | 不等于 | {status: _.neq('deleted')} |
gt | 大于 | {score: _.gt(80)} |
gte | 大于等于 | {age: _.gte(18)} |
lt | 小于 | {price: _.lt(100)} |
lte | 小于等于 | {discount: _.lte(0.5)} |
in | 在数组中 | {category: _.in(['tech', 'news'])} |
nin | 不在数组中 | {status: _.nin(['deleted', 'banned'])} |
🔍 查询数据
单条查询
通过文档 ID 查询指定记录。
参数说明
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
docId | string | ✅ 是 | 文档的唯一标识符 |
代码示例
// 根据文档 ID 查询单条记录
const result = await db.collection('todos')
.doc('docId')
.get()
console.log('查询结果:', result.data)
返回结果
{
data: {
_id: "todo-id-123",
title: "学习 CloudBase",
completed: false,
// ... 其他字段
},
errMsg: "document.get:ok"
}
多条查询
查询集合中的多条记录,支持条件筛选、排序、分页等。
参数说明
方法 | 参数类型 | 必填 | 说明 |
---|---|---|---|
where() | object | ❌ 否 | 查询条件,支持操作符 |
orderBy() | string, string | ❌ 否 | 排序字段和方向('asc' 或 'desc') |
limit() | number | ❌ 否 | 限制返回记录数, 默认 100 条, 最多返回 1000 条 |
skip() | number | ❌ 否 | 跳过记录数,用于分页 |
field() | object | ❌ 否 | 指定返回字段,true 表示返回,false 表示不返回 |
// 查询所有记录
const result = await db.collection('todos').get()
console.log('查询结果:', result.data)
// 条件查询
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()
console.log(`第 ${pageNum} 页数据:`, result.data)
聚合查询
// 统计查询
const result = await db.collection('todos')
.aggregate()
.group({
_id: '$priority',
count: {
$sum: 1
}
})
.end()
console.log('按优先级统计:', result.list)
➕ 新增数据
单条新增
向集合中添加一条新记录。
参数说明
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
data | object | ✅ 是 | 要新增的数据对象 |
代码示例
// 添加单条记录
const result = await db.collection('todos').add({
data: {
title: '学习 CloudBase',
content: '完成数据库操作教程',
completed: false,
priority: 'high',
createdAt: new Date(),
tags: ['学习', '技术']
}
})
console.log('新增成功,文档 ID:', result._id)
批量新增
一次性向集合中添加多条记录。
参数说明
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
data | array | ✅ 是 | 包含多个数据对象的数组,每个对象包含 data 字段 |
代码示例
// 批量添加多条记录
const batchResult = await db.collection('todos').add([{
data: {
title: '任务1',
priority: 'high',
completed: false
}
},
{
data: {
title: '任务2',
priority: 'medium',
completed: false
}
}
])
console.log('批量新增成功:', batchResult)
📝 更新数据
单条更新
通过文档 ID 更新指定记录。
参数说明
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
docId | string | ✅ 是 | 要更新的文档 ID |
data | object | ✅ 是 | 要更新的数据对象 |
代码示例
// 更新指定文档
const result = await db.collection('todos')
.doc('todo-id')
.update({
data: {
title: '学习 CloudBase 数据库',
completed: true,
updatedAt: new Date(),
completedBy: 'user123'
}
})
console.log('更新成功,影响记录数:', result.stats.updated)
批量更新
根据查询条件批量更新多条记录。
参数说明
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
where | object | ✅ 是 | 查询条件,确定要更新的记录 |
data | object | ✅ 是 | 要更新的数据对象 |
代码示例
// 批量更新多条记录
const batchResult = await db.collection('todos')
.where({
completed: false,
priority: 'low'
})
.update({
data: {
priority: 'normal',
updatedAt: new Date()
}
})
console.log('批量更新结果:', batchResult)
🗑️ 删除数据
单条删除
通过文档 ID 删除指定记录。
参数说明
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
docId | string | ✅ 是 | 要删除的文档 ID |
代码示例
// 删除指定文档
const result = await db.collection('todos')
.doc('todo-id')
.remove()
console.log('删除成功,影响记录数:', result.stats.removed)
批量删除
根据查询条件批量删除多条记录。
参数说明
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
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()
console.log('批量删除结果:', batchResult)
⚠️ 注意事项
错误处理
所有数据库操作都应该使用 try-catch 进行错误处理:
try {
const result = await db.collection('todos').get()
console.log('查询成功:', result.data)
} catch (error) {
console.error('查询失败:', error)
}
重要提醒
注意事项 | 说明 | 建议 |
---|---|---|
权限控制 | 确保已正确配置数据库安全规则 | 使用最小权限原则 |
数据校验 | 在客户端和服务端都要进行数据校验 | 防止无效数据入库 |
性能优化 | 合理使用索引和查询条件 | 避免全表扫描 |
💡 最佳实践
数据结构设计
- 合理设计集合结构:避免过度嵌套,保持数据结构清晰
- 建立索引:为常用查询字段建立索引提升性能
- 数据类型:使用合适的数据类型,如日期使用 时间戳
查询优化
- 限制返回数据量:使用
limit()
控制返回记录数 - 字段投影:使用
field()
只返回需要的字段
安全考虑
- 安全规则:配置合适的数据库安全规则
- 输入验证:验证用户输入数据的合法性
- 敏感信息:避免在客户端存储敏感信息