小程序云数据库增加操作 - 课程总结笔记
一、增加数据的基本方法
1. 核心API:add()
javascript
db.collection('集合名').add({
data: {
字段1: 值1,
字段2: 值2,
// ... 其他字段
}
})
2. 完整添加示例
javascript
// 连接到user集合并添加数据
db.collection('user').add({
data: {
username: 'SAKURA',
age: 20,
jobs: '上学堂·小米',
icon: '图片地址'
}
}).then(res => {
console.log('添加成功:', res)
}).catch(err => {
console.error('添加失败:', err)
})
二、添加操作的完整流程
1. 添加按钮触发
xml
<!-- WXML -->
<button type="primary" bindtap="addData">添加数据</button>
2. 添加函数实现
javascript
// JS
addData: function() {
const db = wx.cloud.database()
db.collection('user').add({
data: {
username: 'SAKURA',
age: 20,
jobs: '上学堂·小米',
icon: 'https://example.com/avatar.jpg'
}
}).then(res => {
console.log('添加成功:', res)
// 添加成功后重新获取数据
this.getData()
}).catch(err => {
console.error('添加失败:', err)
})
}
3. 添加结果说明
javascript
// 添加成功返回的结果
{
_id: "新生成的数据ID", // 系统自动生成的唯一标识
errMsg: "collection.add:ok" // 成功信息
}
// 通过errMsg判断是否成功
if (res.errMsg === "collection.add:ok") {
console.log('数据添加成功')
}
三、数据渲染到页面
1. 获取并存储数据
javascript
// 获取数据的函数
getData: function() {
const db = wx.cloud.database()
db.collection('user')
.limit(20) // 限制获取条数
.get()
.then(res => {
// 将数据存储到页面data中
this.setData({
list: res.data
})
})
.catch(err => {
console.error('获取数据失败:', err)
})
}
// 在页面加载时调用
onLoad: function() {
this.getData()
}
2. 渲染数据到页面
xml
<!-- WXML 渲染列表 -->
<view wx:for="{{list}}" wx:key="_id" class="item">
<!-- 图片 -->
<image src="{{item.icon}}" style="width: 50px; height: 70px;"></image>
<!-- 文本信息 -->
<view>
<text>姓名: {{item.username}}</text>
<text>年龄: {{item.age}}</text>
<text>工作: {{item.jobs}}</text>
</view>
</view>
四、实现添加后实时更新
方案1:添加成功后重新查询
javascript
addData: function() {
const db = wx.cloud.database()
// 1. 添加数据
db.collection('user').add({
data: {
// 数据字段...
}
}).then(res => {
// 2. 判断是否添加成功
if (res.errMsg === "collection.add:ok") {
// 3. 重新获取数据
this.getData()
}
})
}
方案2:优化用户体验
javascript
addData: function() {
// 显示加载提示
wx.showLoading({
title: '添加中...',
})
const db = wx.cloud.database()
db.collection('user').add({
data: {
// 数据字段...
}
}).then(res => {
// 隐藏加载提示
wx.hideLoading()
if (res.errMsg === "collection.add:ok") {
// 显示成功提示
wx.showToast({
title: '添加成功',
icon: 'success',
duration: 1500
})
// 重新获取数据
this.getData()
}
}).catch(err => {
wx.hideLoading()
wx.showToast({
title: '添加失败',
icon: 'error',
duration: 2000
})
console.error('添加失败:', err)
})
}
五、重要注意事项
1. 数据去重问题
- 相同内容可以重复添加 :只要
_id不同,相同内容的数据可以重复添加 - 系统自动生成_id :每次添加操作都会生成一个唯一的
_id
2. 字段一致性
javascript
// 确保添加的字段与集合结构一致
// 数据库中的字段:username, age, jobs, icon
add({
data: {
username: '张三', // √ 正确
age: 25, // √ 正确
job: '工程师', // × 错误(应该是jobs)
icon: '' // √ 正确(可为空)
}
})
3. 图片地址处理
- 存储图片地址时,确保地址是有效的URL
- 可以从云存储获取文件地址,或使用外部图片链接
六、完整示例代码
页面结构(WXML)
xml
<view class="container">
<!-- 添加按钮 -->
<button type="primary" bindtap="addData">添加数据</button>
<!-- 数据列表 -->
<view class="list">
<view wx:for="{{list}}" wx:key="_id" class="item">
<image src="{{item.icon}}" class="avatar"></image>
<view class="info">
<text class="name">{{item.username}}</text>
<text class="age">年龄: {{item.age}}</text>
<text class="jobs">{{item.jobs}}</text>
</view>
</view>
</view>
</view>
页面逻辑(JS)
javascript
Page({
data: {
list: [] // 存储数据列表
},
onLoad: function() {
// 页面加载时获取数据
this.getData()
},
// 获取数据函数
getData: function() {
const db = wx.cloud.database()
db.collection('user')
.limit(20)
.get()
.then(res => {
this.setData({
list: res.data
})
})
.catch(err => {
console.error('获取数据失败:', err)
wx.showToast({
title: '数据加载失败',
icon: 'none'
})
})
},
// 添加数据函数
addData: function() {
// 显示加载提示
wx.showLoading({
title: '添加中...',
})
const db = wx.cloud.database()
db.collection('user').add({
data: {
username: 'SAKURA',
age: 20,
jobs: '上学堂·小米',
icon: 'https://example.com/avatar.jpg'
}
}).then(res => {
wx.hideLoading()
if (res.errMsg === "collection.add:ok") {
wx.showToast({
title: '添加成功',
icon: 'success'
})
// 重新获取数据
this.getData()
}
}).catch(err => {
wx.hideLoading()
wx.showToast({
title: '添加失败',
icon: 'error'
})
console.error('添加失败:', err)
})
}
})
页面样式(WXSS)
css
/* 列表项样式 */
.item {
display: flex;
align-items: center;
padding: 15px;
border-bottom: 1px solid #eee;
}
/* 头像样式 */
.avatar {
width: 50px;
height: 70px;
border-radius: 5px;
margin-right: 15px;
}
/* 信息区域 */
.info {
display: flex;
flex-direction: column;
}
.name {
font-size: 16px;
font-weight: bold;
margin-bottom: 5px;
}
.age, .jobs {
font-size: 14px;
color: #666;
margin-bottom: 3px;
}
七、最佳实践建议
1. 用户体验优化
- 添加操作前进行表单验证
- 添加过程中显示加载状态
- 添加成功或失败给予明确反馈
2. 数据管理
- 合理设计数据结构,避免冗余字段
- 对于频繁更新的数据,考虑使用局部更新而非重新查询全部
- 定期清理无效或过期数据
3. 错误处理
javascript
// 完整的错误处理
addData: function() {
// ... 添加逻辑 ...
.catch(err => {
console.error('添加失败详情:', err)
// 根据错误类型给出不同提示
if (err.errCode === -1) {
wx.showToast({
title: '网络错误,请检查连接',
icon: 'none'
})
} else {
wx.showToast({
title: '操作失败,请重试',
icon: 'none'
})
}
})
}
4. 性能考虑
- 大量数据添加时使用批量操作(后续课程会讲)
- 避免在循环中频繁调用add()方法
- 考虑使用云函数处理复杂的数据添加逻辑
八、核心知识点回顾
- 添加数据 :
collection.add({data: {...}}) - 自动生成_id:系统为每条新数据生成唯一标识
- 添加成功判断 :通过
res.errMsg === "collection.add:ok"判断 - 数据实时更新:添加成功后重新查询并更新页面
- 用户体验:添加过程中的加载提示和结果反馈
通过掌握这些操作,可以实现小程序与云数据库的完整数据交互流程:添加数据 → 查询数据 → 渲染展示。这是小程序开发中最基础也是最重要的数据操作技能。