微信小程序雲開發


微信小程序雲開發

一、開發准備

新建項目選擇一個空目錄,填入AppID

1.project.confg.json中增加了字段cloudfunctionRoot用於指定存放雲函數的目錄,在項目根目錄下創建cloud文件夾

    "description": "項目配置文件",
    "cloudfunctionRoot": "cloud",

2.在app.js中進行初始化雲開發

App({
  onLaunch() {
    wx.cloud.init({
      env: 'cloud1-4gydzrjnd3e45911',	//環境ID來自於,雲開發->設置->環境ID
      traceUser:true
    })
  }
})

3.連接數據庫,在該頁面的最上面引入雲數據庫。

const db = wx.cloud.database()

二、雲數據庫

初始化

在開始使用數據庫 API 進行增刪改查操作之前,需要先獲取數據庫的引用。以下調用獲取默認環境的數據庫的引用:

const db = wx.cloud.database()

要操作一個集合,需先獲取它的引用。在獲取了數據庫的引用后,就可以通過數據庫引用上的 collection 方法獲取一個集合的引用了,比如獲取待辦事項清單集合:

const todos = db.collection('todos')

插入數據

可以通過在集合對象上調用 add 方法往集合中插入一條記錄。

data: {
    val:""
  },
  pushIpt:function(e){
    var val = e.detail.value;
    this.setData({
      val:val
    })
  },
  btnAdd: function () {
    db.collection("clouddemo").add({
      data: {
        name: this.data.val,
        contact: "10010",
      },
      success: (res) => {
        console.log(res);
      },
    });
  },

刪除數據

對記錄使用 remove 方法可以刪除該條記錄,比如:

  btnDel: function () {
      // doc 只能根據id來刪除
    db.collection("clouddemo")
      .doc("cd045e756121062906fee3a50e67faf1")
      .remove({
        success: (res) => {
          console.log(res);
        },
      });

      // where 可以根據條件來刪除
    db.collection("clouddemo")
      .where({ name: "王五" })
      .remove({
        success: (res) => {
          console.log(res);
        },
      });
  },

更新數據

API 說明
update 局部更新一個或多個記錄
set 替換更新一個記錄

局部更新

使用 update 方法可以局部更新一個記錄或一個集合中的記錄,局部更新意味着只有指定的字段會得到更新,其他字段不受影響。

  btnUpdata() {
    db.collection("clouddemo")
      .doc("cd045e7561210f9607003923228201bb")
      .update({
        data: {
          name: "羅翔",
          contact:"110",
          qq:666,
          posttime:new Date()
        },
        success: res => {
          console.log(res);
        },
      });
	},

替換更新

如果需要替換更新一條記錄,可以在記錄上使用 set 方法,替換更新意味着用傳入的對象替換指定的記錄:

  btnUpdata() {          db.collection("clouddemo")      .doc("cd045e7561210fc80700412f7b901154")      .set({        data: {          name: "塔姆",        },        success: (res) => {          console.log(res);        },      });  },

查詢數據

在記錄和集合上都有提供 get 方法用於獲取單個記錄或集合中多個記錄的數據。

  btnGet() {    db.collection("clouddemo")      .where({        name: "羅翔",      })      .get()      .then((res) => {        console.log(res);        this.setData({          getArr: res.data,        });      });  },

查詢條件

limit指定查詢結果集數量上限

skip指定查詢返回結果時從指定序列后的結果開始返回,常用於分頁

orderBy方法接受一個必填字符串參數 fieldName 用於定義需要排序的字段,一個字符串參數 order 定義排序順序。

field方法接受一個必填對象用於指定需返回的字段,對象的各個 key 表示要返回或不要返回的字段

觸底查詢新內容

  getLimit(sp=0) {    this.setData({      page:sp    })    db.collection("clouddemo")      .limit(4)      .skip(sp*4)      .get()      .then((res) => {        console.log(res.data);      });  },              onReachBottom: function () {    let page = this.data.page;    page++;    this.getLimit(page);  },

查詢條件限制

  //查詢條件限制  getLimit(sp = 0) {    this.setData({      page: sp,    });    // db.collection("clouddemo")    //   .limit(4)    //   .skip(sp * 4)    //   .get()    //   .then((res) => {    //     console.log(res.data);    //   });    db.collection("clouddemo")      .orderBy("age", "desc")      .orderBy("_id", "desc")      .field({        name: true,        age:true      })      .get()      .then((res) => {        console.log(res.data);      });  },

count統計匹配查詢條件的記錄的條數

get獲取集合數據,或獲取根據查詢條件篩選后的集合數據

  // 獲取個數的方法  getListArr() {    // db.collection("clouddemo")    //   .get()    //   .then((res) => {    //     console.log(res.data.length);    //   });    db.collection("clouddemo")      .count()      .then((res) => {        console.log(res.total);      });  },

watch監聽集合中符合查詢條件的數據的更新事件。使用 watch 時,支持 where, orderBy, limit,不支持 field

  // 在頁面中渲染數據  getArr() {    db.collection("clouddemo")      .get()      .then((res) => {        this.setData({          dataArr: res.data,        });      });  },       this.getArr();    db.collection("clouddemo")      .watch({        onChange: (res) => {          this.setData({            dataArr: res.docs,          });        },        onError: (err) => {          console.log(err);        },      });

Command

數據庫操作符,通過 db.command 獲取

查詢·比較操作符
// 鏈接數據庫const db = wx.cloud.database();const _ = db.command;getQuery() {    db.collection("clouddemo")      .where({        // name:_.eq("小紅")    查詢姓名等於小紅的        // name:_.neq("小紅")   查詢姓名不等於小紅的        // age: _.lt(18),       查詢年齡小於18的        // age: _.gt(18),       查詢年齡大於18的        // age: _.in([18,21])   查詢在這個數組里的        age: _.nin([18,21])      })      .get()      .then((res) => {        // console.log(res);        this.setData({          dataArr: res.data,        });      });  },
查詢·邏輯操作符
  getQuery() {    db.collection("clouddemo")      .where({        // age:_.gt(16).and(_.lt(24))   查詢操作符,用於表示邏輯 "與" 的關系,表示需同時滿足多個查詢篩選條件        // age: _.eq(18).or(_.eq(21)),  查詢操作符,用於表示邏輯 "或" 的關系,表示需同時滿足多個查詢篩選條件。        // age: _.eq(18).not(_.eq(21)), 查詢操作符,用於表示邏輯 "非" 的關系,表示需不滿足指定的條件。        // age: _.eq(18).nor(_.eq(21)), 查詢操作符,用於表示邏輯 "都不" 的關系,表示需不滿足指定的所有條件。      })      .get()      .then((res) => {        // console.log(res);        this.setData({          dataArr: res.data,        });      });  },

and還可以用在根查詢條件

  getQuery2() {    db.collection("clouddemo")      .where(        _.and(          {            name: "小紅",          },          {            age: _.gt(20),          }        )      )      .get()      .then((res) => {        // console.log(res);        this.setData({          dataArr: res.data,        });      });  },
查詢·數組操作符
  getQuery3() {    db.collection("clouddemo")      .where({        // like: _.all(["跑步"]),   數組查詢操作符。用於數組字段的查詢篩選條件,要求數組字段中包含給定數組的所有元素。        // like:_.size(2)       用於數組字段的查詢篩選條件,要求數組中包含至少一個滿足 elemMatch 給定的所有條件的元素      })      .get()      .then((res) => {        // console.log(res);        this.setData({          dataArr: res.data,        });      });  },
更新·字段操作符
  getQuery4() {    db.collection("clouddemo")      .doc("cd045e7561210f9607003923228201bb")      .update({        data: {          // qq: _.remove(), 更新操作符,用於表示刪除某個字段          // age: _.inc(10), 更新操作符,原子操作,用於指示字段自增        },      })      .then((res) => {        // console.log(res);        this.setData({          dataArr: res.data,        });      });  },
更新·數組操作符
  getQuery5() {    db.collection("clouddemo")      .doc("cd045e7561210f9607003923228201bb")      .update({        data: {          // like: _.unshift(["aaa", "bbb"]), 對一個值為數組的字段,往數組頭部添加一個或多個值          // like: _.shift(),     對一個值為數組的字段,將數組頭部元素刪除。          // like: _.push(["打籃球","社會搖"]),     對一個值為數組的字段,往數組添加一個或多個值          // like: _.pop(),     對一個值為數組的字段,將數組尾部元素刪除          // like: _.push({          //   each:["旅行"],          //   position:1,    從第二個位置開始插入          //   sort:-1        排序          // }),          // like: _.pull("l")    給定一個值或一個查詢條件,將數組中所有匹配給定值或查詢條件的元素都移除掉。        },      })      .then((res) => {        // console.log(res);        this.setData({          dataArr: res.data,        });      });  },

三、雲函數

1、基本使用

1、創建雲函數

image-20210824161746550

2、寫雲函數

// 雲函數入口文件const cloud = require("wx-server-sdk");cloud.init();// 雲函數入口函數exports.main = async (event, context) => {    return event.a + event.b;};

3、上傳並且部署

image-20210824161841349

4、綁定雲函數

    // 獲取數據    getData(){        wx.cloud.callFunction({     //雲函數使用            name:"demo",            //綁定函數的名字            data:{                  //發送過去的數據                a:123,                b:456            },            success:res=>{          //成功回調                console.log(res);            }        })    },

2、雲函數處理數據庫

雲函數端

// 雲函數入口文件const cloud = require("wx-server-sdk");cloud.init();// 連接數據庫const db = cloud.database();// 雲函數入口函數exports.main = async (event, context) => {    return await db.collection("clouddemo").count()};

小程序端

    getData() {        wx.cloud.callFunction({            //雲函數使用            name: "demo", //綁定函數的名字            success: (res) => {                console.log(res.result.total);                this.setData({                    num:res.result.total	//保存獲取的數據                })            },            fail: console.error        });    },

async和await

    async getThen() {        console.log("11");        const getDb = await db.collection("clouddemo").get();        console.log(getDb);    },

雲函數添加數據

小程序端

    getData() {        wx.cloud.callFunction({                name: "demo", //綁定函數的名字                data: {                    name: this.data.iptVal                },            }).then(res => {                console.log(res);            });    },    // 獲取表單數據    bindIpt(e) {        // console.log(e.detail.value);        this.setData({            iptVal: e.detail.value,        });    },

雲函數端

// 雲函數入口文件const cloud = require("wx-server-sdk");cloud.init();// 連接數據庫const db = cloud.database();// 雲函數入口函數exports.main = async (event, context) => {    const wxContext = cloud.getWXContext()    var name = event.name;    return await db.collection("clouddemo").add({        data: {            _openid: wxContext.OPENID,            name: name,            posttime: db.serverDate()        },    });};

四、雲存儲

1、存儲圖片到雲存儲中

    // 獲取雲函數數據    clickBtn() {        wx.cloud            .callFunction({                name: "demo2",            })            .then((res) => {                console.log(res.result.data);                this.setData({                    dataArr: res.result.data,                });            });    },    // 上傳圖片    onUpload() {        wx.chooseImage({            sizeType: ["original", "compressed"],            sourceType: ["album", "camera"],        }).then((res) => {            console.log(res.tempFilePaths);            this.setData({                fileTem: res.tempFilePaths,            });        });    },            // 上傳雲存儲    cloudFile() {        var fileTem = this.data.fileTem;        if (fileTem.length > 0) {            fileTem.forEach((item, idx) => {                wx.cloud                    .uploadFile({                        cloudPath: new Date().getTime() + "_" + idx + ".jpg",                        filePath: item,                    })                    .then((res) => {                        console.log(res);                    })                    .catch((err) => {                        console.log(err);                    });            });        }    },    // 關閉圖像按鈕    onClost(e) {        var idx = e.currentTarget.dataset.idx;        var fileTem = this.data.fileTem;        fileTem.splice(idx, 1);        this.setData({            fileTem: fileTem,        });    },

2、存儲視頻到雲存儲中

    // 選擇視頻    getVideo() {        wx.chooseVideo({            sourceType: ["album", "camera"],            maxDuration: 60,            camera: "back",            success: (res) => {                // console.log(res.tempFilePath);                wx.showLoading({                    title: "加載中",                });                this.fileCloud(res.tempFilePath, new Date().getTime());            },        });    },    // 上傳視頻    fileCloud(tem, file) {        wx.cloud.uploadFile({            cloudPath: file + ".mp4",            filePath: tem,            success: (res) => {                // console.log(res.fileID);                if (res.fileID) {                    wx.hideLoading();                }                this.setData({                    videoSrc: res.fileID,                });            },            fail: console.error,        });    },

五、案例

const db = wx.cloud.database();Page({    /**     * 頁面的初始數據     */    data: {        iptVal: "",        upFileAll: [],        cloudFile: [],    },    // 獲取輸入框內容    bindIpt(e) {        console.log(e.detail.value);        this.setData({            iptVal: e.detail.value,        });    },    // 選擇文件    upFile() {        wx.chooseMessageFile({            success: (res) => {                console.log(res.tempFiles);                this.setData({                    upFileAll: res.tempFiles,                });            },        });    },    // 點擊提交    onSubmit() {        wx.showLoading({            title: "發布中,請稍后",        });        var upFileAll = this.data.upFileAll;        upFileAll.forEach((item, idx) => {            var tem = item.path;            var filename = item.time + "_" + idx + "_" + item.name;            this.cloudFile(tem, filename, idx);        });    },    // 發送到雲存儲    cloudFile(tem, filename, idx) {        wx.cloud            .uploadFile({                cloudPath: filename,                filePath: tem,            })            .then((res) => {                this.data.upFileAll[idx].path = res.fileID;                this.data.cloudFile.push(res);                if (this.data.upFileAll.length == this.data.cloudFile.length) {                    this.pushDb();                }                // console.log(this.data.cloudFile);            });    },    // 發送到數據庫    pushDb() {        db.collection("demo")            .add({                data: {                    title: this.data.iptVal,                    upFileAll: this.data.upFileAll,                    posttime: new Date(),                },            })            .then((res) => {                wx.hideLoading();                wx.showToast({                    title: "發表成功",                    icon: "success",                    success: (res) => {                        this.getListFile();                    },                });            });    },    // 渲染初始化列表    getListFile() {        db.collection("demo")            .get()            .then((res) => {                // console.log(res);                this.setData({                    fileList: res.data,                });            });    },    // 下載文件    downFile(e) {        var fileid = e.currentTarget.dataset.fileid;        console.log(fileid);        wx.cloud            .downloadFile({                fileID: fileid,            })            .then((res) => {                // console.log(res.tempFilePath);                wx.openDocument({                    filePath: res.tempFilePath,                    success: function (res) {                        console.log("打開文檔成功");                    },                });            });    },    onLoad: function (options) {        this.getListFile();    },});


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM