1.新建项目时不使用云服务,
image.png
2.在app.js初始化项目
image.png
3.新建云函数
image.png
4.在服务器新建list
image.png
5云服务端clouefunctions右键下新建nide.js云函数,写上文件名,
image.png
在这里我命名为chaxun
image.png
6在chaxun文件下的index.js中
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db=cloud.database()
// 细节:init要在db之前
// 客户端获取db,就要加wx. 云函数端获取db,就不能加wx.
// 云函数入口函数
exports.main = async (event, context) => {
// 任何一个云函数文件,必须返回一个东西
// 在云函数中sonsole.log()是没有意义的
// 查询数据
return db.collection('todos').get().then(res => {
return res;
})
}
客户端的代码
1 wxml中
<button type="primary" bindtap="searchDataFn">查询数据</button>
<button type="primary" bindtap="insertDataFn">插入数据</button>
<button type="primary" bindtap="addMoreDataFn">插入多条数据</button>
<button type="primary" bindtap="removeDataFn">删除一条数据</button>
<button type="primary" bindtap="updateDataFn">修改数据</button>
2 js中连接数据库
// 连接数据库
const db = wx.cloud.database()
3.js中查数据库的函数**
// 点击按钮查询数据
searchDataFn(){
// 查询所有文件的方式
// 可写条件
db.collection('todos').get().then(res => {
// res.data 包含该记录的数据
console.log(res)
})
},
4.js中插入数据库的方法
// 插入数据
insertDataFn(){
db.collection('todos').add({
data: {
username: "李四",
age: 37
}
}).then(res=>{
console.log(res)
})
},
5.js中插入多条数据数据的方法
// 插入多条数据
addToMenu(id, bool) {
return new Promise((resolve, reject) => {
let db = wx.cloud.database()
db.collection('todos').add({
data: {
_id: id,
done: bool
}
}).then(res=>{
resolve(res);
})
})
},
// 公用的插入数据方法
insertTotal(username, age){
return new Promise((resolve, reject)=>{
db.collection('todos').add({
data: {
username: username,
age: age
}
}).then(res=>{
resolve(res)
})
})
},
// 插入多条数据
addMoreDataFn(){
let _this = this;
async function fn(){
await _this.insertTotal("Lucy", 18);
await _this.insertTotal("Jack", 20);
await _this.insertTotal("龙哥", 18);
}
// 调用异步方法
fn();
},
6删除数据
// 删除数据
removeDataFn(){
db.collection('todos').where({
username: "李四"
}).remove().then(res=>{
console.log(res)
})
// db.collection('test').doc('e373396c5f640cc50009918c49c99d36').remove().then(res=>{
// console.log(res)
// })
},
修改数据
// 修改数据
updateDataFn(){
db.collection('todos').where({
username: "龙哥"
}).update({
data: {
username: "小龙"
}
}).then(res=>{
console.log(res)
})
},