小程序学习(三) 之云开发(未完待续)
1、初始化
(一)
// 获取默认环境:
const db = wx.cloud.database()
(二)
// 获取指定环境,假设环境为test:
const testDB = wx.cloud.database({
env: 'test'
})
2、操作云数据库中某个集合
// 获取云数据库中的用户集合 user
const user = db.collection('user')
3、新增
// 新增(Promise风格)
user.add({
data: {
name: '李雷',
age: 18
}
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
// 或
user.add({
data: {
name: '李雷',
age: 18
},
success(res) {
console.log(res)
},
fail (err) {
console.log(err)
}
})
4、删除
(一)删除单条数据
// 删除1条 id 为 7d79-ef94 的数据 // 1.先读取到指定id的用户信息 db.collection('user').doc('7d79-ef94') 。 // 2.调用remove()方法删除。 db.collection('user').doc('7d79-ef94').remove().then(res => { console.log(res) }).catch(err => { console.log(err) })
// 或 user.doc('7d79-ef94').remove({ success (res) { console.log(res) }, fail (err ) { console.log(err) } })
(二)删除多条数据
5、修改
// 修改1条 id 为 7d79-ef94 的数据 // 1.先读取到指定id的用户信息 db.collection('user').doc('7d79-ef94') 。 // 2.调用update()方法。 db.collection('user').doc('7d79-ef94').update({ data: { name: '李雷', age: 22 } }).then(res => { console.log(res) }).catch(err => { console.log(err) })
6、查询
(一)获取单条数据(详情)
// 获取指定id的用户信息,假设id = 'abc-09k' wx.collection('user').doc('abc-09k').get().then(res => { console.log(res) }).catch(err => { console.log(err) }) // 或 wx.collection('user').doc('abc-09k').get({ success (res) { console.log(res) }, fail (err) { console.log(err) } })
(二)获取多条数据(列表)
// where方法指定查询的条件
// where接收一个对象参数,这个对象参数的每一个字段作为查询条件,而且这些查询字段之间的关系为“并”,也就是同时满足查询条件的所有字段的数据才会被返回。
wx.collection('user').where({
age: 18,
sex: '男'
}).get().then(res => {}).catch(err => {})
/* 数据库中user集合中数据示例:*/ user: [ { name: '李雷', age: 18, sex: '男', hobby: ['游泳', '旅行', '画画'], feature: { color: 'yellow', height: 180, size: 'XL' } }, { name: '韩梅梅', age: 17, sex: '女', hobby: ['旅行', '音乐'], feature: { color: 'yellow', height: 162, size: 'M' } }, { name: '刘洋', age: 18, sex: '男', hobby: ['电影', '篮球'], feature: { color: 'yellow', height: 186, size: 'XXL' } } ] /* 读取age为18并且feature的color值为'yellow'的数据返回 */ // (一)指定匹配一个嵌套字段的值 wx.collection('user').where({ age: 18, feature: { color: 'yellow' } }).get().then(res => {}).catch(err => {}) // (二)用 "点表示法" 表示嵌套字段 wx.collection('user').where({ age: 18, 'feature.color': 'yellow' }).get().then(res => {}).catch(err => {})