小程序云开发学习笔记
- 初始化
在app.js里面 小程序一开始就初始化,多次调用只有第一次触发
onLaunch() {
console.log("小程序打开");
wx.cloud.init({
env: 'ayang-8g50ew302a3a6c5a', //云开发id
})
}
- 数据库操作
- 查询(一定要配置数据权限,否则可能请求不到)
常规写法
wx.cloud.database().collection('goods').get({
//wx.cloud.database()是初始化函数,也可以定义一个实例来操作数据库
success: function (res) {
// res.data 包含该记录的数据
console.log("请求成功", res.data)
},
fail(err) {
console.log("请求失败", err)
}
})
es6写法(支持then)
wx.cloud.database().collection('goods').get().then(res => {
console.log(res.data);
}).catch(err => {
console.log(err);
})
- 传统写法和es6写法的区别
传统写法中的this指向父亲函数不是window
箭头函数没有this,它的this继承于它创建的作用域下的this
- 选择查询 //用上where
wx.cloud.database().collection('goods').where({
name: '苹果'
}).get().then(res=>{})
- doc查询 //doc 里面放数据的_id 且不能为空
wx.cloud.database().collection('goods').doc('f6e08a6462a55ee307a613306cd59003').get().then()
-
- 添加数据
wx.cloud.database().collection('goods')
.add({
//添加数据
data: {
name: "香交",
price: '321'
}
}).then().catch()
-
- 修改数据 //必须配上查询条件要不报错
wx.cloud.database().collection('goods').where({
_id: 'ca780ad562a9826e07511a73023c3b02'
})
.update({
//修改数据
data: {
name: "香交",
price: '32123123231'
}
}).then()
-
- 删除 //必须配上查询条件
wx.cloud.database().collection('goods').where({
name: '香交'
})
.remove().then()
-
- 排序 orderBy 里面必须传两个值,第一个为要根据谁排序,第二个是排序规则正序倒序 asc 或者 desc
wx.cloud.database().collection('goods').orderBy('price','asc').get().then()
6.limit限制数据条数
wx.cloud.database().collection('goods').orderBy('price','asc').limit(1).get().then(res => {
console.log(res);
}).catch(err => {
console.log(err);
})
7.skip从第几条数据开始
wx.cloud.database().collection('num')
.limit(2)//限制读两条数据
.skip(0)//从第0条以后的数据开始
.get().then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
- command高级筛选
- 大于
let db=wx.cloud.database()
db.collection('goods').where({
price:db.command.gt(50)
}).get().then(res=>{
console.log(res)
})
-
- 小于
let db=wx.cloud.database()
db.collection('goods').where({
price:db.command.lt(50)
}).get().then(res=>{
console.log(res)
})
-
- 多条件筛选
let db = wx.cloud.database()
const _=db.command
db.collection('goods').where(
_.and([{
price: _.gt(20)
}, {
price: _.lt(40)
}])
).get().then(res => {
console.log(res)
})
- 云函数
- 初始化环境
(1)创建一个文件夹cloud与pages平齐
- 在project.config.json里面配置云函数所在目录为cloud
然后点击保存,我们的cloud文件夹前面就有一个云朵
- 新建云函数