微信小程序云开发
云开发优势
- 无需搭建服务器
- 免登录、免鉴权调用微信开放服务
- 统一开发多端应用
- 不限开发语言和框架
上手
创建一个集合
点击云开发打开云开发控制台点开数据库创建一个新的集合
在集合中点击插入字段插入数据
{
// 描述,String 类型
"description": "learn mini-program cloud service",
// 截止时间,Date 类型
"due": Date("2018-09-01"),
// 标签,Array 类型
"tags": [
"tech",
"mini-program",
"cloud"
],
// 个性化样式,Object 类型
"style": {
"color": "red"
},
// 是否已完成,Boolean 类型
"done": false
}
在资源环境下创建一个Node.js云函数并在index.js中添加代码
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
// 自己的环境id
env: 'tacp-2gbybh5e077c4887',
traceUser: true
})
// 获取数据库的引用
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
// 获取一个集合的引用
let res = await db.collection('todos').add({
data: {
description: "今天周一",
due: new Date(),
tags: [
"cloud",
"database"
],
location: new db.Geo.Point(113, 23),
done: false
}
})
return res
}
云函数编写完成后点击右键进行上传并部署
如果修改完index.js中的代码还需上传可以在index.js上右键点击云函数增量上传:更新文件
在pages中新建页面text并添加按钮
<button type="submit" bindtap="cloud_add">云函数添加</button>
在text.js中编写代码
async cloud_add(){
let res=await wx.cloud.callFunction({
// 云函数的名字
name:'add'
})
console.log(res);
},
点击按钮后查看云开发控制台中的数据库
对数据进行单条查询
创建一个新的node.js云函数并在index.js中编写如下代码
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
env: 'tacp-2gbybh5e077c4887',
traceUser: true
})
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
let res=await db.collection('todos').doc('17453ede60865ee5045ac9363ec46efc').get()
return res
}
在text页面添加一个新的按钮
<button type="submit" bindtap="get_odd">获取单条数据</button>
在text.js中编写代码
async get_odd(){
let res=await wx.cloud.callFunction({
name:'get_odd'
})
console.log(res);
},
点击按钮后查看控制台console的输出
对数据进行多条查询
创建一个新的node.js云函数并在index.js中编写如下代码
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
env: 'tacp-2gbybh5e077c4887',
traceUser: true
})
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
let res=await db.collection('todos').where({
description:event.description
}).get()
return res
}
在text页面添加一个新的按钮
<button type="submit" bindtap="get_odds">获取多条数据</button>
在text.js中编写代码
async get_odds(){
let res=await wx.cloud.callFunction({
name:'get_odds',
description:'今天周一'
})
console.log(res);
},
点击按钮后查看控制台console的输出