微信小程序云开发(2)— 云数据库

数据库的初始化

在开始使用数据库API进行增删改查操作前,先要获取数据库的引用。
调用获取默认环境的数据库引用:

const db = wx.cloud.database()

之后就可以在方法获取集合的引用了

db.collection("这里是集合的名称")

查询,获取一个记录的数据

假设我们已经有一个ID为 "1135396392"的集合在demolist上的记录,那么我们可以调用get方法获取数据

db.collection("demolist").doc("1135396392")
.get()
.then(res=>{
   console.log(res)
})

this.setData可以渲染到前端
js文件中添加

db.collection("demolist").doc("1135396392")
.get()
.then(res=>{
   console.log(res)
   this.setData({
     dataObj:res.data
   })
})

在wxml中比如说要将data里的标题输出

<view>{{dataObj.title}}</view>

查询指令 where

比如我要查询一个叫“达达利亚”的作者

db.collection("demolist").where({
   author:"达达利亚"
})
.get()
.then(res=>{
   console.log(res)
})

插入 添加数据到云数据库(add方法)

可以通过在集合对象调用add方法往集合中插入一条记录

    addData(){
        db.collection("demolist")
        .add({
            data:{
                title:"测试标题",
                author:"DanownWang",
                content:"这是测试内容"
            }
        })
    },

提交表单添加到云数据库

wxml

<form bindsubmit="btnSub">
  <input name="title" placeholder="请输入标题:">标题:</input>
  <input name="author" placeholder="请输入作者:">作者:</input>
  <textarea name="content" placeholder="请输入内容:"></textarea>
  <button type="primary" form-type="submit">提交</button>
  <button form-type="reset">重置</button>
</form>

js

    //提交表单到云数据库
    btnSub(res){
        var{title,author,content} = res.detail.value  //解构方法
        db.collection("demolist")
        .add({
            data:{
                title,
                author,
                content
            }
        })
    },

也可以直接传入一个对象,具体操作:

    btnSub(res){
        var resVul = res.detail.value
        db.collection("demolist")
        .add({
            data:resVul
        })
    },

更新云数据库

  • update 局部更新一个或多个记录(只有指定字段更新)
  • set 替换更新一个记录(覆盖)

(1)update

eg:查找id修改

    upData(){
        db.collection("demolist").doc("14139e12615db7441167d8fa6b45469f")
        .update({
            data:{
                author:"王"
            }
        })
    },

eg:定位条件修改(将作者是“菜”的改成“王”)

    upData(){
        db.collection("demolist")
        .where({
            author:"菜"
        })
        .update({
            data:{
                author:"王"
            }
        })
    },

(2)set

    upData(){
        db.collection("demolist").doc("14139e12615db7441167d8fa6b45469f")
        .set({
            data:{
                author:"王"
            }
        })
    },

用set更新的结果是doc(“14139e12615db7441167d8fa6b45469f”)记录里只有author这条数据了。

删除数据记录

删除一条数据

对记录使用remove方法可以删掉一条数据记录
eg:删除指定id的记录

    upData(){
        db.collection("demolist").doc("14139")
        .remove()
    },

删除多条数据

注意: 若删除多条记录,需要在云函数端进行。可以通过where语句选取多条记录执行删除,只有有权限删除的记录会被删除。
eg:删除集合里所有author为“王”的记录
部署云函数

// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database();
const _ = db.command;

// 云函数入口函数
exports.main = async (event, context) => {
    return await db.collection("demolist")
    .where({
        author:"王"
    })
    .remove()
}

在wxml设置按钮

<button bindtap="DelList">删除多条记录</button>

在js文件中调用云函数

    //删除多条记录
    DelList(){
        wx.cloud.callFunction({
            name:"demoDelList"
        })
    },
获取用户输入的id删除对应记录

bindinput用户输入时触发,event.detail = {value, cursor, keyCode},keyCode 为键值
wxml

<input bindinput="myVul" placeholder="请输入要删除的id"></input>
<button  bindtap="upData">删除</button>

js

const db = wx.cloud.database();
var vul = ""           //!!定义全局变量


    //获取用户输入的id
    myVul(res){
        var myVul = res.detail.value  //接收用户输入的
        vul = myVul                  //传给全局变量
    },
        //删除数据
    upData(){
        db.collection("demolist").doc(vul)  //全局变量可以其他函数中使用
        .remove()
    },

获取记录个数(count)

  • 小程序端:与集合权限设置有关,一个用户仅能统计其有读权限的记录
  • 云函数端:因属于管理端,因此可以统计集合的所有记录数

eg:获取记录中作者为“腾讯新闻”的记录个数。

    btnCount(){
        db.collection("demolist")
        .where({
            author:"腾讯新闻"
        })
        .count()
        .then(res=>{
            console.log("数量是:"+res.total)
        })
    },

进一步,获取用户输入的作者名称的记录个数。

wxml文件

<input bindinput="couVul" placeholder="请输入作者:"></input>
<button bindtap="btnCount" type="primary">点击获取</button>

js文件

    //获取个数
    couVul(res){
        //console.log(res)
        var couVul = res.detail.value
        cVul = couVul
    },
    btnCount(){
        db.collection("demolist")
        .where({
            author:cVul
        })
        .count()
        .then(res=>{
            console.log("数量是:"+res.total)
        })
    },


数据监听(watch)

监听集合中符合查询条件的数据的更新事件。使用watch时,支持whereorderBylimit,不支持field

  • onChange 成功回调(必填)
  • onError 失败回调(必填)
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        db.collection("demolist").watch({
            onChange:res=>{
                console.log(res)
            },
            onError:err=>{
                console.log(err)
            }
        })
    },

eg:通过watch监听data数据的变化,数据发生变化时,就会打印当前的值。

wxml
在页面上显示

<view wx:for="{{dataArr}}">{{index+1}}.{{item.author}}</view>

js

    //获取数据 配合监听 可视化
    getData(){
        db.collection("demolist")
        .get()
        .then(res=>{
            this.setData({
                dataArr:res.data
            })
        })
    },

/**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.getData()   //调用

        db.collection("demolist").watch({
            onChange:res=>{
                console.log(res.docs)
                this.setData({         //!更新了数据,一点就打印进来了
                    dataArr:res.docs
                })
            },
            onError:err=>{
                console.log(err)
            }
        })
    },

watch监听可以做到及时更新数据。

  • 3
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值