小程序 云开发 数据库操作
开发者可以使用云开发开发微信小程序、小游戏,无需搭建服务器,即可使用云端能力。
云开发为开发者提供完整的云端支持,弱化后端和运维概念,无需搭建服务器,使用平台提供的 API 进行核心业务开发,即可实现快速上线和迭代,同时这一能力,同开发者已经使用的云服务相互兼容,并不互斥。
目前提供三大基础能力支持:
1、云函数:在云端运行的代码,微信私有协议天然鉴权,开发者只需编写自身业务逻辑代码
2、数据库:一个既可在小程序前端操作,也能在云函数中读写的 JSON 数据库
3、存储:在小程序前端直接上传/下载云端文件,在云开发控制台可视化管理
具体的可以去小程序文档上查看,下面用一个登录注册的案例来演示小程序云开发数据库的运用
注册
在创建的时候,要在点下一步的时候,调数据库来看用户名有没有重复的。在点击同意的时候来调用数据库,然后把所有的判断放到下一步来判断。所有条件都满足就将用户名和密码放到全局变量中。
-
// 同意
-
checkboxChange: function() {
-
if (this.data.checkbox === false) {
-
this.setData({
-
checkbox: true
-
})
-
} else {
-
this.setData({
-
checkbox: false
-
})
-
}
-
var that = this;
-
var userName = this.data.userName;
-
// 初始化云
-
wx.cloud.init({
-
env: 'wubaib-9543f7',
-
traceUser: true
-
});
-
// 初始化数据库
-
const db = wx.cloud.database();
-
const _ = db.command;
-
db.collection('userInformation').where({
-
userName: _.eq(userName)
-
}).get({
-
success: function (res) {
-
if (res.data.length === 1) {
-
that.setData({
-
repetition: true
-
})
-
}
-
}
-
})
-
},
在完善信息的时候获取所有的变量(用户名和密码也在内),然后在点击下一步完成按钮将数据上传到数据库。
-
// 初始化云
-
wx.cloud.init({
-
env: 'wubaib-9543f7',
-
traceUser: true
-
});
-
// 初始化数据库
-
const db = wx.cloud.database();
-
db.collection('userInformation').add({
-
// data 字段表示需新增的 JSON 数据
-
data: {
-
realName: realName,
-
userName: userName,
-
userPassword: userPassword,
-
phone: phone,
-
email: email,
-
card: card
-
},
-
success: function(res) {
-
// res 是一个对象,其中有 _id 字段标记刚创建的记录的 id
-
console.log(res);
-
console.log(res.errMsg);
-
}
-
})
登录
在登录页面,先获取用户输入的用户名和密码。在点击登录的时候,先根据userName调数据库的密码和用户输入的密码是否相等。如果相等将用户的信息保存到全局变量中。
-
// 点击登录
-
bindingSuccess: function() {
-
var that = this;
-
var bindName = that.data.bindName;
-
var bindPassword = that.data.bindPassword;
-
if (bindName.length !== 0 && bindPassword.length !== 0) {
-
// 初始化云
-
wx.cloud.init({
-
env: 'wubaib-9543f7',
-
traceUser: true
-
});
-
// 初始化数据库
-
const db = wx.cloud.database();
-
db.collection('userInformation').where({
-
userName: bindName
-
}).get().then(res => {
-
console.log(res.data);
-
if (res.data[0].userPassword === bindPassword) {
-
console.log("登录成功");
-
// 保存手机号,真实姓名,身份证号,邮箱 保存用户名
-
that.setData({
-
userName: res.data[0].userName,
-
phone: res.data[0].phone,
-
realName: res.data[0].realName,
-
card: res.data[0].card,
-
email: res.data[0].email,
-
userId: res.data[0]._id
-
})
-
app.appData.userinfo = {
-
phone: that.data.phone,
-
realName: that.data.realName,
-
card: that.data.card,
-
email: that.data.email
-
}
-
app.appData.account = {
-
userName: that.data.userName
-
}
-
app.appData.userId = {
-
userId: that.data.userId
-
}
-
wx.switchTab({
-
url: '../personalCenter/personalCenter',
-
})
-
} else {
-
wx.showToast({
-
title: '用户名或密码错误',
-
icon: 'none',
-
duration: 2000
-
})
-
}
-
})
-
}
-
},
--------------------- 本文来自 一个减肥的小胖子 的**** 博客 ,全文地址请点击:https://blog.****.net/qq_40999496/article/details/82773484?utm_source=copy