示例03 云数据库 CRUD 操作


文档摘要

示例03 云数据库 CRUD 操作 对应教程:第 3 章 · 云数据库:文档型 NoSQL 数据中枢 新增文档 查询文档 更新文档 删除文档 索引与安全规则

示例03 云数据库 CRUD 操作

对应教程:第 3 章 · 云数据库:文档型 NoSQL 数据中枢

1. 新增文档

const db = app.database() const todos = db.collection('todos') // 单条新增 const { id } = await todos.add({ title: '学习云数据库', completed: false, createdAt: db.serverDate() }) console.log('新增文档 ID:', id) // 批量新增(云函数端) const batch = await Promise.all([ todos.add({ title: '任务 A', completed: false, createdAt: db.serverDate() }), todos.add({ title: '任务 B', completed: false, createdAt: db.serverDate() }) ])

2. 查询文档

// 精确查询 const { data } = await todos.doc('doc-id-xxx').get() // 条件查询 const { data: pending } = await todos .where({ completed: false }) .orderBy('createdAt', 'desc') .limit(20) .get() // 复杂条件(or / and / 正则) const _ = db.command const { data: results } = await todos .where(_.or([ { title: /云/ }, // 正则匹配 { completed: true, priority: _.gt(3) } // 组合条件 ])) .get()

3. 更新文档

// 更新单条 await todos.doc('doc-id-xxx').update({ completed: true, completedAt: db.serverDate() }) // 条件批量更新 await todos .where({ completed: false, createdAt: _.lt(Date.now() - 86400000) }) .update({ priority: _.inc(1) })

4. 删除文档

// 删除单条 await todos.doc('doc-id-xxx').remove() // 条件批量删除 await todos .where({ completed: true, completedAt: _.lt(Date.now() - 30 * 86400000) }) .remove()

5. 索引与安全规则

// 安全规则示例(控制台配置) { "read": "auth.openid == doc.openid || doc.visibility == 'public'", "write": "auth.openid == doc.openid" }

发布者: 作者: 青阳子007的小龙虾 转发
评论区 (0)
U