如何在微信云开发对数据库的增删改查

 

一、app.js中初始化微信云数据库

// app.js
App({
  onLaunch: function () {
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力');
    } else {
      wx.cloud.init({
        // env 参数说明:
        //   env 参数决定接下来小程序发起的云开发调用(wx.cloud.xxx)会默认请求到哪个云环境的资源
        //   此处请填入环境 ID, 环境 ID 可打开云控制台查看
        //   如不填则使用默认环境(第一个创建的环境)
        env: 'coderlh-2ggd3le3583f41ee',
        traceUser: false,//是否跟踪用户 是否将用户访问记录存储到云端

      });
    }
    this.globalData = {};
  }
});

二、我们创建数据库并创建对应的集合

由于我们对所有的数据库进行增删改查操作我们就把这个方法写在page对象外面方便调用

在这里我有两个数据表一个是学生表一个是斗鱼的数据(学习用的)

// 获取数据库
const db = wx.cloud.database();
//要操作的集合
const studentCollection = db.collection("student");
const douyucollection = db.collection("douyu");

三、增加数据

 add() {
    //对这个集合新增学生表
    studentCollection
      .add({
        data: {
          name: "李霓1",
          age: 25,
          sex: "false",
          address: {
            name: "重庆",
            code: 4000,
          },
          hobbies: ["跳舞", "唱歌", "跑步"],
        },
        //1 可以通过这种方式判断是否成功 自己使用代码进行添加的数据是有openid 唯一用户标识就是可以跟
        // success: (res) => {
        //   console.log(res);
        // },
      })
      //2 promise 也可以判断是否成功 也可以对其使用async
      .then((res) => {
        console.log(res);
      });
//斗鱼数据(学习用的)

  adddouyu() {
    for (let index = 0; index < 10; index++) {
      wx.request({
        url: `https://m.douyu.com/api/room/list?page=${index + 1}&type=yz`,
        success: (result) => {
          this.handleAddList(result.data.data.list);
        },
        fail: () => {},
      });
    }
  },
  handleAddList(list) {
    for (const item of list) {
      douyucollection
        .add({
          data: item,
        })
        .then((res) => {
          console.log(res);
        });
    }
  },

三、删除数据

 delete() {
    // 明确的知道删除某一条数据 根据id来删除
    // studentCollection
    //   .doc("93e4b6a0643f8c6d093a705e3d27453d")
    //   .remove()
    //   .then((res) => {
    //     console.log(res);
    //   });
    // 根据条件,查询到数据的结果进行删除 比如名字等于李霓
    // age》24
    const cmd = db.command;
    studentCollection
      .where({
        // name: "li",
        age: cmd.gt(24),
      })
      .remove()
      .then((res) => {
        console.log(res);
      });
  },

四、更新数据

  update() {
    // doc 是明确的更新,具体更新那一条数据 where是有条件的更新更新范围 update方式
    // studentCollection
    //   .doc("fe89b8da643fa4b60006ea3066a6d97b")
    //   .update({
    //     data: {
    //       age: "修改后的年龄",
    //     },
    //   })
    //   .then((res) => {
    //     console.log(res);jav
    //   });
    //set方法是直接将你传入的对象替换掉原来的 而update是直接更新
    // studentCollection
    //   .doc("28f2b5f2643fa5170017f5082f3a65a0")
    //   .set({
    //     data: {
    //       age: "修改后的年龄",
    //     },
    //   })
    //   .then((res) => {
    //     console.log(res);
    //   });
    /**
     * 更新多条数据
     */
    const cmd = db.command;
    studentCollection
      .where({
        age: cmd.gt(24),
      })
      .update({
        data: { age: "更新过后的年龄" },
      })
      .then((res) => {
        console.log(res);
      });
  },

四、更新数据

 query() {
    // 明确的知道要查哪一个数据使用doc
    // douyucollection
    //   .doc("f85f4996643fb1b60018ef425f1e4543")
    //   .get()
    //   .then((res) => {
    //     console.log(res);
    //   });
    // 根据条件查询 where
    // douyucollection
    //   .where({
    //     nickname: "安小主暴富",
    //   })
    //   .get()
    //   .then((res) => {
    //     console.log(res);
    //   });
    /**方式三:查询指令 gt大于 lt小于 */
    // const cmd = db.command;
    // douyucollection
    //   .where({
    //     rid: cmd.lt(9727168),
    //   })
    //   .get()
    //   .then((res) => {
    //     console.log(res);
    //   });
    /**方式四正则表达式模糊查询 */
    // douyucollection
    //   .where({
    //     nickname: db.RegExp({
    //       regexp: "安",
    //       options: "i",
    //     }),
    //   })
    //   .get()
    //   .then((res) => {
    //     console.log(res);
    //   });
    /**
     * 获取集合中所有数据
     * 只返回前20
     */
    // douyucollection.get().then((res) => {
    //   console.log(res);
    // });
    /**分页 skip(offset) limit(size) */
    // let page = 1;
    // douyucollection
    //   .skip(page * 5) //这个就是偏移5条就是前5条不要,要后五条
    //   .limit(5)
    //   .get()
    //   .then((res) => {
    //     console.log(res);
    //   });
    /**排序orderby 房间号排序
     *  必须指明升序还是降序
     * field 我们查询完只有这几个字段
     * */
    let page = 1;
    douyucollection
      .field({
        _id: true,
        nickname: true,
        rid: true,
      })
      .skip(page * 5)
      .limit(5)
      .orderBy("rid", "desc")
      .get()
      .then((res) => {
        console.log(res);
      });
  },

五、查询指令where条件里面可以跟许多条件


总结

不管是关系型数据库还是非关系型数据库,对数据库的操作增删改查都很重要没有一些代码可能写的不是很严谨,请多多包涵!!!!!

猜你喜欢

转载自blog.csdn.net/m0_70718568/article/details/130254998