微信小程序云开发服务端数据库API 更新指令


本文整理自网络,侵删。

db.command.set

更新指令。用于设定字段等于指定值。

函数签名:

function set(value: any): Command

这种方法相比传入纯 JS 对象的好处是能够指定字段等于一个对象:

const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
exports.main = async (event, context) => {
  try {
    // 以下方法只会更新 style.color 为 red,而不是将 style 更新为 { color: 'red' },即不影响 style 中的其他字段
    const res1 = await db.collection('todos').doc('doc-id').update({
      data: {
        style: {
          color: 'red'
        }
      }
    })

    // 以下方法更新 style 为 { color: 'red', size: 'large' }
    const res2 = await db.collection('todos').doc('doc-id').update({
      data: {
        style: _.set({
          color: 'red',
          size: 'large'
        })
      }
    })

    return {
      res1,
      res2,
    }
  } catch(e) {
    console.error(e)
  }
}

db.command.remove

更新指令。用于表示删除某个字段。

函数签名:

function remove(): Command

示例代码

删除 style 字段:

const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command
exports.main = async (event, context) => {
  try {
    return await db.collection('todos').doc('todo-id').update({
      data: {
        style: _.remove()
      }
    })
  } catch(e) {
    console.error(e)
  }
}

db.command.inc

更新指令。用于指示字段自增某个值,这是个原子操作,使用这个操作指令而不是先读数据、再加、再写回的好处是:

  1. 原子性:多个用户同时写,对数据库来说都是将字段加一,不会有后来者覆写前者的情况
  2. 减少一次网络请求:不需先读再写

mul 指令同理。

函数签名:

function inc(value: number): Command

示例代码

将一个 todo 的进度自增 10:

const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command
exports.main = async (event, context) => {
  try {
    return await db.collection('todos').doc('todo-id').update({
      data: {
        progress: _.inc(10)
      }
    })
  } catch(e) {
    console.error(e)
  }
}

db.command.mul

更新指令。用于指示字段自乘某个值,这是个原子操作,使用这个操作指令而不是先读数据、再加、再写回的好处是:

  1. 原子性:多个用户同时写,对数据库来说都是将字段自乘,不会有后来者覆写前者的情况
  2. 减少一次网络请求:不需先读再写

inc 指令同理。

函数签名:

function mul(value: number): Command

示例代码

阅读剩余部分

相关阅读 >>

微信小程序 扩展组件仿微信表情组件

多端开发kbone

微信小程序 快递接口(商家查看)-下载打单软件

sdk数据库 command查询表达式操作符

微信小程序媒体组件 image

微信小程序 getvisitpage

微信小程序api 背景

微信小程序api 相机-创建cameracontext对象

微信小程序 小程序直播-其他能力

微信小程序 wi-fi

更多相关阅读请进入《微信小程序》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...