小程式 雲開發 資料庫操作
開發者可以使用雲開發開發微信小程式、小遊戲,無需搭建伺服器,即可使用雲端能力。
雲開發為開發者提供完整的雲端支援,弱化後端和運維概念,無需搭建伺服器,使用平臺提供的 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
-
})
-
}
-
})
-
}
-
},
--------------------- 本文來自 一個減肥的小胖子 的CSDN 部落格 ,全文地址請點選:https://blog.csdn.net/qq_40999496/article/details/82773484?utm_source=copy