微信云开发 - 常见数据库查询命令操作

534 阅读6分钟

云数据库命令

详情请参考微信官方文档 - 增删改查SDK

连接数据库

const db = wx.cloud.database()

建立表连接

db.collection("表名称")

常用命令

增删改查

命令说明参数
get查询命令对象
add插入命令对象
update更新/修改对象
.set()修改/覆盖数据对象
.remove()删除数据
.count()数据表中数据个数
.watch()监听数据表中数据变化

查询命令

命令说明参数
.doc()根据ID查询云数据库自动生成的id
.where()查询指令对象
.set()修改/覆盖数据对象

get - 查询

const db = wx.cloud.database;

page({
    getData(){
        db.collection("demolist").get()
          .then(res => {
            console.log('获取全部数据',res)
        })
    },
})

add - 插入

  addData(){
    // 插入记录
    wx.showLoading({
      title: '数据加载中...',
      mask:true
    })
    db.collection("demolist").add({
      data:{
        title:"震惊,隔壁老王竟然。。。",
        author:"隔壁老李",
        content:"炎炎烈日,朗朗乾坤之下,隔壁老王竟然做出如此令人难以启齿的事儿!",
        time:new Date(),
        tabs:["新闻"]
      }
    }).then(res => {
      console.log(res);
      wx.hideLoading()
    })
  },

输入插入数据

// wxml
<view>
  <form bindsubmit="btnSub">
    <input name="title" placeholder="请输入标题" type="text"/>
    <input name="author" placeholder="请输入作者" type="text"/>
    <textarea name="content" placeholder="请输入内容" type="text"/>
    <button type="primary" form-type="submit">提交</button>
    <button type="primary" form-type="reset">重置</button>
  </form>
</view>
// js
 btnSub(res){
    console.log(res);
    let {author,content,title} = res.detail.value
    db.collection("demolist").add({
      data:{
        author,
        content,
        title
      }
    }).then(res=> {
      console.log(res);
    })
  },

update - 更新/修改数据

// js
  updateData(){
    // 使用update必须要带条件
    // db.collection("demolist").doc("98bd709665d2ca79009b21ce056a160a").update({
    //   data:{
    //     author:"虎大王"
    //   }
    // }).then(res => {
    //   console.log(res);
    // })
    // 小程序端只能使用doc,where在云函数中使用
    db.collection("demolist").where({
      author:"虎大王"
    }).update({
      data:{
        author:"虎虎生威"
      }
    }).then(res => {
      console.log(res);
    })
  },

set - 更新/覆盖

用法类似于update只不过会覆盖掉原来的数据

remove - 删除

delData(){       
    db.collection("demolist").doc("98bd709665d2ca79009b21ce056a160a").remove()
      .then(res => {
        console.log(res);
      })
  },

同样在使用云函数时用where添加条件筛选,在小程序端只能使用doc根据id删除,返回removed:1表示删除成功

获取数据库数据个数 - count

  // 获取记录个数
  getCount(){
    // db.collection("demolist").get()
    //   .then(res => {})
    db.collection("demolist").count()
      .then(res => {
        console.log(res);
      })
  },

watch - 监听数据表中数据变化

onLoad: function (options) {
    db.collection("demolist").watch({
      onChange:res => {
        console.log(res);
      },
      onError:err => {
        console.log(err);
      }
    })
  },

docChanges - 发生变化的数据 - 数组

docs - 数据表中所有已更新的数据

数据更新watch自动触发 - 默认自动触发

promise方式

解决回调地狱问题

// 原来的方式
db.collection("").get({
    success:res=>{
        console.log(res);
    }
})
// promise方式
db.collection("").get()
    .then(res => {})
    .then(res => {})
    .catch(err => {})
​
///////////////////
db.collection("demolist").get()
      .then(res => {
        return db.collection("demolist").doc(res.data[0]._id).get()
      })
      .then(res=> {
        console.log(res);
      })

查询指令

where命令

db.collection("demolist").where({
      author:"老王观察"
}).get()
  .then(res=> {
    console.log(res);// 返回的是一个数组
})

查询条件

命令说明参数
.limit(number)获取多少条数据number
.orderBy(string,string)排序指定字段,排序方式("asc","desc")
.skip(number)从第几条开始展示(分页)number
.field(object)获取指定字段对象

.limit(number) - 获取指定数量数据

getData(){
    db.collection("demolist").limit(3).get()
      .then(res => {
        console.log(res);
      })
  },

.orderBy(string,string)

getData(){ db.collection("demolist").limit(3).orderBy("time","asc").get()
      .then(res => {
        console.log(res);
      })
  },

.skip(number)

 getData(){
    db.collection("demolist").limit(3).skip(3).get()
      .then(res => {
        console.log(res);
      })
  },

.field(object)

getData(){
    db.collection("demolist").limit(3).field({
      title:true,
      author:true
    }).get()
      .then(res => {
        console.log(res);
      })
  },

command - 查询条件

const db = wx.cloud.database();

const _ = db.command;

常用

比较条件筛选

方法说明参数
.eq()筛选条件,等于某值时
.neq()筛选条件,不等于某值时
.lt()小于
.lte()小于等于
.gt()大于
.gte()大于等于
.in()筛选条件,值在给定的数组内
.nin()筛选条件,值不在给定的数组内
.exists()判断字段是否存在
getData(){
    db.collection("demolist").where({
      hits:_.eq(200)
    }).get()
      .then(res => {
        console.log(res);
      })
  },
 // 多条件附加
getData(){
    db.collection("demolist").where({
      hits:_.lt(4000).gt(200)
    }).get()
      .then(res => {
        console.log(res);
      })
  },

逻辑条件筛选

命令说明参数
.and()逻辑与
.or()逻辑或
.not()逻辑非
.nor()逻辑都不
getData(){
    db.collection("demolist").where({
      hits:_.nor(_.lt(4000).gt(200))
    }).get()
      .then(res => {
        console.log(res);
      })
  },

注意:当使用.nor时筛选字段如果不存在也会符合条件,不会报错!

当筛选条件不止是一个字段时

where(查询条件)

getData(){
    db.collection("demolist").where(_.nor([
      {
        hits:_.lt(1000)
      },
      {
        author:_.eq('老王观察')
      }
    ]))
    .get()
    .then(res => {
      console.log(res);
    })
  },

数组

命令说明参数
.all()查询数组字段中包含给定数组的所有元素(同时包含某某条件)any[]
.elemMatch()查询数组中至少包含一个满足elemMatch给定的所有条件的元素Object
.size()查询数组字段中符合给定数组长度的数据string
.all()
// 查询tabs字段中含有“新闻”的数据
db.collection("demolist")
    .where({
      tabs:_.all(["新闻"])
    })
    .get()
    .then(res => {
      console.log(res);
    })
.elemMatch({})

针对对象数组进行的查询方法

// 找出 places 数组字段中至少同时包含一个满足 “area 大于 100 且 age 小于 2” 的元素
const _ = db.command
db.collection('todos').where({
  places: _.elemMatch({
    area: _.gt(100),
    age: _.lt(2),
  })
})
.get()
.size()
// 查询tabs中长度为2的数据
db.collection("demolist")
    .where({
      tabs:_.size(2)
    })
    .get()
    .then(res => {
      console.log(res);
    })

补充

existe - 判断字段是否存在

db.collection("demolist")
    .where({
      time:_.exists(true)
    })
    .get()
    .then(res => {
      console.log(res);
    })

更新 - 字段

命令说明参数
.set()设定某字段等于给定值(会覆盖原数据)
.remove()删除
.inc()自增/自减
.mul()自乘某值
.min()小于给定值时更新
.max()大于给定值时更新
.rename()字段重命名

update方式更新

updateDate(){
    db.collection("demolist")
    .doc("4940644865d2b8ad00971b075b183b41")
    .update({
      data:{
        title:"标题已更新"
      }
    })
    .then(res => {
      console.log(res);
    })
  },

对于控制台添加(没有openid字段)的数据因为权限问题无法更新

.set - 更新数据(覆盖原数据)

// 会删除掉没有指定的数据
updateDate(){
    db.collection("demolist")
    .doc("4201187e65d2c722009a7f285fae5d28")
    .update({
      data:{
        style:_.set({
          color:"pink"
        })
      }
    })
    .then(res => {
      console.log(res);
    })
  },
// 当不需要覆盖时
updateDate(){
    db.collection("demolist")
    .doc("4201187e65d2c722009a7f285fae5d28")
    .update({
      data:{
        style:{
          color:"#bfa",
          size:"20px"
        }
      }
    })
    .then(res => {
      console.log(res);
    })
  },

.remove() - 删除

updateDate(){
    db.collection("demolist")
    .doc("4201187e65d2c722009a7f285fae5d28")
    .update({
      data:{
        // hits:_.inc(5)//hits:_.inc(-6)
        time:_.remove()
      }
    })
    .then(res => {
      console.log(res);
    })
  },

.inc() - 自增/自减

 updateDate(){
    db.collection("demolist")
    .doc("4201187e65d2c722009a7f285fae5d28")
    .update({
      data:{
        hits:_.inc(5)//hits:_.inc(-6)
      }
    })
    .then(res => {
      console.log(res);
    })
  },

。。。

更新 - 数组

命令说明参数
.push()往数组中添加一个或多个值,如果字段为空,则创建该字段
.pop()删除数组尾部元素
.unshift()往数组头部添加一个或多个值,如果为空,则创建该字段
.shift()删除数组第一个元素
.pull()删除数组中所有匹配条件的元素
.pullAll()删除数组中所有匹配条件的元素,只能给定常量值
.addToSet()更新数组。原子操作,添加

.push()

updateDate(){
    db.collection("demolist")
    .doc("4201187e65d2c722009a7f285fae5d28")
    .update({
      data:{
        tabs:_.push(["吃瓜"])
      }
    })
    .then(res => {
      console.log(res);
    })
  },