目录
更改数据权限
初始化
1 初始化:获取所需数据库的引用
调用获取默认环境的数据库的引用
const db = wx.cloud.database()
获取其他环境的数据库引用
const testDB = wx.cloud.database({
env: 'test'
})
2 获取数据库所需集合的引用
const todos = db.collection('todos')
集合的 doc 方法 获取集合中一个指定 ID 的记录的引用
const todo = db.collection('todos').doc('todo-identifiant-aleatoire')
数据库增删改查
增
// data 字段表示需新增的 JSON 数据
// userInfo1:{}
// 增 用户信息
var userInfo1=e.detail.userInfo
console.log(userInfo1);
db.collection('userInfo').add({
data: userInfo1
})
.then(res => {
console.log(res)
})
删
删除一条记录
db.collection('todos').doc('todo-identifiant-aleatoire').remove({
success: function(res) {
console.log(res.data)
}
})
删除多个数据
需在 Server 端进行操作(云函数)。可通过 where 语句选取多条记录执行删除,只有有权限删除的记录会被删除。比如删除所有已完成的待办事项:
在大多数情况下,我们希望用户只能操作自己的数据(自己的代表事项),不能操作其他人的数据(其他人的待办事项),这就需要引入权限控制了。
// 使用了 async await 语法
const cloud = require('wx-server-sdk')
const db = cloud.database()
const _ = db.command
exports.main = async (event, context) => {
try {
return await db.collection('todos').where({
done: true
}).remove()
} catch(e) {
console.error(e)
}
}
改
API | 作用 |
---|---|
update | 局部改一个或多个记录 |
set | 覆盖 |
局部更新(指定字段更新)
意味着只有指定的字段会得到更新
比如我们可以用以下代码将一个待办事项置为已完成:
db.collection('todos').doc('todo-identifiant-aleatoire').update({
// data 传入需要局部更新的数据
data: {
// 表示将 done 字段置为 true
done: true
},
success: function(res) {
console.log(res.data)
}
})
匹配某项,更新整条记录
const _ = db.command
var avatarUrlLogining = e.detail.userInfo.avatarUrl;
var userIfoLogining = e.detail.userInfo
console.log(avatarUrlLogining);
console.log(userIfoLogining);
db.collection('userInfo').where({
avatarUrl: avatarUrlLogining
}).update({
data: userIfoLogining
}).then(res => {
console.log(res)
})
db.command
db.command改 | 说明 |
---|---|
set | 设置字段为指定值 |
remove | 删除字段 |
inc | 原子自增字段值 |
mul | 原子自乘字段值 |
push | 如字段值为数组,往数组尾部增加指定值 |
pop | 如字段值为数组,从数组尾部删除一个元素 |
shift | 如字段值为数组,从数组头部删除一个元素 |
unshift | 如字段值为数组,往数组头部增加指定值 |
将一个待办事项的进度 +10%:
用 inc 指令而不是取出值、加 10 再写进去的好处在于这个写操作是个原子操作,不会受到并发写的影响,比如同时有两名用户 A 和 B 取了同一个字段值,然后分别加上 10 和 20 再写进数据库,那么这个字段最终结果会是加了 20 而不是 30。如果使用 inc 指令则不会有这个问题。
const _ = db.command
db.collection('todos').doc('todo-identifiant-aleatoire').update({
data: {
// 表示指示数据库将字段自增 10
progress: _.inc(10)
},
success: function(res) {
console.log(res.data)
}
})
数组 push、pop、shift 和 unshift
给一条待办事项加多一个标签:
const _ = db.command
db.collection('todos').doc('todo-identifiant-aleatoire').update({
data: {
tags: _.push('mini-program')
},
success: function(res) {
console.log(res.data)
}
})
Set
增加属性
更新一个字段值为另一个对象。比如如下语句是更新 style.color 字段为 ‘blue’ 而不是把 style 字段更新为 {color: ‘blue’ } 对象,就是增加的意思:
const _ = db.command
db.collection('todos').doc('todo-identifiant-aleatoire').update({
data: {
style: {
color: 'blue'
}
},
success: function(res) {
console.log(res.data)
}
})
覆盖
如果需要将这个 style 字段更新为另一个对象,可以使用 set 指令:
const _ = db.command
db.collection('todos').doc('todo-identifiant-aleatoire').update({
data: {
style: _.set({
color: 'blue'
})
},
success: function(res) {
console.log(res.data)
}
})
更新多个数据
需在 Server 端进行操作(云函数)
在 where 语句后同样的调用 update 方法即可,比如将所有未完待办事项的进度加 10%:
// 使用了 async await 语法
const cloud = require('wx-server-sdk')
const db = cloud.database()
const _ = db.command
exports.main = async (event, context) => {
try {
return await db.collection('todos').where({
done: false
})
.update({
data: {
progress: _.inc(10)
},
})
} catch(e) {
console.error(e)
}
}
替换更新
替换更新意味着用传入的对象替换指定的记录: 如果指定 ID的记录不存在,则会自动创建该记录,该记录将拥有指定的 ID。
const _ = db.command
db.collection('todos').doc('todo-identifiant-aleatoire').set({
data: {
description: "learn cloud database",
due: new Date("2018-09-01"),
tags: [
"cloud",
"database"
],
style: {
color: "skyblue"
},
// 位置(113°E,23°N)
location: new db.Geo.Point(113, 23),
done: false
},
success: function(res) {
console.log(res.data)
}
})
查
获取一个记录的数据
db.collection('todos').doc('todo-identifiant-aleatoire').get().then(res => {
// res.data 包含该记录的数据
console.log(res.data)
})
获取多个记录的数据
调用集合上的 where 方法可以指定查询条件
where 方法接收一个对象参数
db.collection('todos').where({
// _openid: 'user-open-id',
// style: {
// color: 'yellow'
// }
_openid: 'user-open-id',
'style.color': 'yellow'
})
.get({
success: function(res) {
console.log(res.data)
}
})
获取一个集合的数据
db.collection('todos').get().then(res => {
// res.data 是一个包含集合中有权限访问的所有记录的数据,不超过 20 条
console.log(res.data)
})
下面是在云函数端获取一个集合所有记录的例子,因为有最多一次取 100 条的限制,因此很可能一个请求无法取出所有数据,需要分批次取:
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const MAX_LIMIT = 100
exports.main = async (event, context) => {
// 先取出集合记录总数
const countResult = await db.collection('todos').count()
const total = countResult.total
// 计算需分几次取
const batchTimes = Math.ceil(total / 100)
// 承载所有读操作的 promise 的数组
const tasks = []
for (let i = 0; i < batchTimes; i++) {
const promise = db.collection('todos').skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
tasks.push(promise)
}
// 等待所有
return (await Promise.all(tasks)).reduce((acc, cur) => {
return {
data: acc.data.concat(cur.data),
errMsg: acc.errMsg,
}
})
}
db.command 大于、小于等多种查询指令
查询指令 | 说明 |
---|---|
eq | 等于 |
neq | 不等于 |
lt | 小于 |
lte | 小于或等于 |
gt | 大于 |
gte | 大于或等于 |
in | 字段值在给定数组中 |
nin | 字段值不在给定数组中 |
and
查询进度在 30% 和 70% 之间的待办事项
const _ = db.command
db.collection('todos').where({
// and 方法用于指定一个 "与" 条件,此处表示需同时满足 _.gt(30) 和 _.lt(70) 两个条件
progress: _.gt(30).and(_.lt(70))
})
.get({
success: function(res) {
console.log(res.data)
}
})
or
查询进度为 0 或 100 的待办事项
const _ = db.command
db.collection('todos').where({
// or 方法用于指定一个 "或" 条件,此处表示需满足 _.eq(0) 或 _.eq(100)
progress: _.eq(0).or(_.eq(100))
})
.get({
success: function(res) {
console.log(res.data)
}
})
跨字段进行 “或” 操作
查询进度小于或等于 50% 或颜色为白色或黄色的待办事项:
const _ = db.command
db.collection('todos').where(_.or([
{
progress: _.lte(50)
},
{
style: {
color: _.in(['white', 'yellow'])
}
}
]))
.get({
success: function(res) {
console.log(res.data)
}
})
上传图片
shangchuan() {
console.log("shangchuan");
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera']
}).then(res => {
console.log(res);
this.shuangchuan1(res.tempFilePaths[0])
})
},
shuangchuan1(filePath) {
wx.cloud.uploadFile({
cloudPath: new Date().getTime()+'.png',
filePath: filePath
}).then(res => {
console.log(res);
})
}
获取时间
// // 2020-02-02T19:27:27.000Z
// console.log(new Date(Date.parse(new Date()) + 60 * 60 * 1000 * 8).toISOString());
// // 2020-02-02
// console.log(new Date(Date.parse(new Date()) + 60 * 60 * 1000 * 8).toISOString().substring(0, 10));