微信小程序云开发------数据库增删改查

云开发

数据库增删改查

初始化

//获取数据库的引用
wx.cloud.database({
  env: 'test'//数据库环境名
})

//获取数据库引用上的集合
wx.cloud.database().collection('todos')
查询

在记录和集合上都有提供 get 方法用于获取单个记录或集合中多个记录的数据。

一、直接调用get()获取所有的记录

二、获取指定的记录

//通过集合上的 doc 方法来获取集合中一个指定 ID 的记录的引用

//方式一:
wx.cloud.database().collection('todos').doc('todo-identifiant-aleatoire').get({
  success: function(res) {
    // res.data 包含该记录的数据
    console.log(res.data)
  }
})

//方式二:
wx.cloud.database().collection('todos').doc('todo-identifiant-aleatoire').get().then(res => {
  // res.data 包含该记录的数据
  console.log(res.data)
})

三、获取多个记录的数据

通过调用集合上的 where 方法可以指定查询条件,再调用 get 方法即可只返回满足指定查询条件的记录

where 方法接收一个对象参数,该对象中每个字段和它的值构成一个需满足的匹配条件,各个字段间的关系是 “与” 的关系,即需同时满足这些匹配条件

wx.cloud.database().collection('todos').where({
  _openid: 'user-open-id',
  'style.color': 'yellow'
})
.get({
  success: function(res) {
    console.log(res.data)
  }
})

开发者可以通过 limit 方法指定需要获取的记录数量,但小程序端不能超过 20 条,云函数端不能超过 100 条。

const $ = wx.cloud.database().command.aggregate
wx.cloud.database().collection('todos').limit(10)
  .get()
  .then(console.log)
  .catch(console.error)

查询指令

数据库 API 提供了大于、小于等多种查询指令,这些指令都暴露在 db.command 对象上。

const _ = wx.cloud.database().command
wx.cloud.database().collection('todos').where({
  // gt 方法用于指定一个 "大于" 条件,此处 _.gt(30) 是一个 "大于 30" 的条件
  progress: _.gt(30)
})
.get({
  success: function(res) {
    console.log(res.data)
  }
})

查询指令	说明
eq	等于
neq	不等于
lt	小于
lte	小于或等于
gt	大于
gte	大于或等于
in	字段值在给定数组中
nin	字段值不在给定数组中

逻辑指令
and  和
or   或
or 指令还可以用来接受多个(可以多于两个)查询条件,表示需满足多个查询条件中的任意一个,
const _ = wx.cloud.database().command
wx.cloud.database().collection('todos').where(_.or([
  {
    progress: _.lte(50)
  },
  {
    style: {
      color: _.in(['white', 'yellow'])
    }
  }
]))
.get({
  success: function(res) {
    console.log(res.data)
  }
})

更多指令

where :指定查询条件,返回带新查询条件的新的集合引用

limit : 指定查询结果集数量上限

orderBy:指定查询排序条件

skip:指定查询返回结果时从指定序列后的结果开始返回,常用于分页

field:指定返回结果中记录需返回的字段

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

方式一:

wx.cloud.database().collection('todos').add({
  // data 字段表示需新增的 JSON 数据
  data: {
    // _id: 'todo-identifiant-aleatoire', // 可选自定义 _id,在此处场景下用数据库自动分配的就可以了
    description: "learn cloud database",
    due: new Date("2018-09-01"),
    tags: [
      "cloud",
      "database"
    ],
    // 为待办事项添加一个地理位置(113°E,23°N)
    location: new db.Geo.Point(113, 23),
    done: false
  },
  success: function(res) {
    // res 是一个对象,其中有 _id 字段标记刚创建的记录的 id
    console.log(res)
  }
})

方式二:

wx.cloud.database().collection('todos').add({
  // data 字段表示需新增的 JSON 数据
  data: {
    description: "learn cloud database",
    due: new Date("2018-09-01"),
    tags: [
      "cloud",
      "database"
    ],
    location: new db.Geo.Point(113, 23),
    done: false
  }
})
.then(res => {
  console.log(res)
})

优化方法
要先查询where ,在修改update

let _this = this
        wx.cloud.database().collection('products').where({
            _id: this.data.id
        }).update({
            // data 字段表示需新增的 JSON 数据
            data: {
                name: _this.data.name,
                num: _this.data.num,
                price: _this.data.price,
                baseUrl: _this.data.baseUrl,
            }
        }).then(res => {
            Toast.success('修改成功');
            this.setData({
                addShow: false
            });
            _this.getProductlist()
        }).catch(err=>{
            Toast.success('修改失败,请重试');
        })

局部更新

使用 update 方法可以局部更新一个记录或一个集合中的记录,局部更新意味着只有指定的字段会得到更新,其他字段不受影响。

wx.cloud.database().collection('todos').doc('todo-identifiant-aleatoire').update({
  // data 传入需要局部更新的数据
  data: {
    // 表示将 done 字段置为 true
    done: true
  },
  success: function(res) {
    console.log(res.data)
  }
})

替换更新

const _ = wx.cloud.database().command
wx.cloud.database().collection('todos').doc('todo-identifiant-aleatoire').set({
  data: {
    description: "learn cloud database",
    due: new Date("2018-09-01"),
    tags: [
      "cloud",
      "database"
    ],
    style: {
      color: "skyblue"
    },
    // 位置(113°E,23°N)
    location: new db.Geo.Point(113, 23),
    done: false
  },
  success: function(res) {
    console.log(res.data)
  }
})

优化删除
先查询where ,再删除

 wx.cloud.database().collection('products').where({
            _id: e.currentTarget.dataset.product._id
        }).remove().then(res=>{
            Toast.success('删除成功');
            _this.getProductlist()
        }).catch(err=>{
            Toast.success('删除失败,请重试');
        })```

删除一条记录

wx.cloud.database().collection(‘todos’).doc(‘todo-identifiant-aleatoire’).remove({
success: function(res) {
console.log(res.data)
}
})


删除多条数据记录

// 使用了 async await 语法
const cloud = require(‘wx-server-sdk’)
const db = cloud.database()
const _ = db.command

exports.main = async (event, context) => {
try {
return await db.collection(‘todos’).where({
done: true
}).remove()
} catch(e) {
console.error(e)
}
}


  • 0
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值