5-1 云开发云数据操作方案:ClientDB
ClientDB 简介
ClientDB 是 uniCloud 提供的前端直连数据库方案,无需编写云函数,前端代码可以直接操作云数据库。
Schema 定义
在 database/ 目录下创建 .schema.json 文件定义数据结构:
{
"bsonType": "object",
"required": ["title", "content"],
"properties": {
"_id": { "description": "ID" },
"title": { "bsonType": "string", "description": "标题" },
"content": { "bsonType": "string", "description": "内容" },
"create_date": { "bsonType": "timestamp", "description": "创建时间" }
}
}
json
前端操作示例
// 获取数据库引用
const db = uniCloud.database()
// 查询数据
const res = await db.collection('articles').get()
// 插入数据
await db.collection('articles').add({
title: '第一篇文章',
content: '这是内容'
})
// 更新数据
await db.collection('articles').doc('article-id').update({
title: '更新后的标题'
})
// 删除数据
await db.collection('articles').doc('article-id').remove()
javascript
权限控制
ClientDB 通过 Schema 中的 permission 字段控制访问权限:
{
"permission": {
"read": true,
"create": "auth.uid != null",
"update": "doc.author_id == auth.uid",
"delete": "doc.author_id == auth.uid"
}
}
json
↑