微信小程序云開發(fā)API 更新指令

2022-05-12 16:11 更新

db.command.set

更新指令。用于設(shè)定字段等于指定值。

函數(shù)簽名:

function set(value: any): Command

這種方法相比傳入純 JS 對象的好處是能夠指定字段等于一個(gè)對象:

// 以下方法只會(huì)更新 style.color 為 red,而不是將 style 更新為 { color: 'red' },即不影響 style 中的其他字段
db.collection('todos').doc('doc-id').update({
  data: {
    style: {
      color: 'red'
    }
  }
})

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

db.command.remove

更新指令。用于表示刪除某個(gè)字段。

函數(shù)簽名:

function remove(): Command

示例代碼

刪除 style 字段:

const _ = db.command
db.collection('todos').doc('todo-id').update({
  data: {
    style: _.remove()
  }
})

db.command.inc

更新指令。用于指示字段自增某個(gè)值,這是個(gè)原子操作,使用這個(gè)操作指令而不是先讀數(shù)據(jù)、再加、再寫回的好處是:

  1. 原子性:多個(gè)用戶同時(shí)寫,對數(shù)據(jù)庫來說都是將字段加一,不會(huì)有后來者覆寫前者的情況
  2. 減少一次網(wǎng)絡(luò)請求:不需先讀再寫

mul 指令同理。

函數(shù)簽名:

function inc(value: number): Command

示例代碼

將一個(gè) todo 的進(jìn)度自增 10:

const _ = db.command
db.collection('todos').doc('todo-id').update({
  data: {
    progress: _.inc(10)
  }
})

db.command.mul

更新指令。用于指示字段自乘某個(gè)值,這是個(gè)原子操作,使用這個(gè)操作指令而不是先讀數(shù)據(jù)、再加、再寫回的好處是:

  1. 原子性:多個(gè)用戶同時(shí)寫,對數(shù)據(jù)庫來說都是將字段自乘,不會(huì)有后來者覆寫前者的情況
  2. 減少一次網(wǎng)絡(luò)請求:不需先讀再寫

inc 指令同理。

函數(shù)簽名:

function mul(value: number): Command

示例代碼

將一個(gè) todo 的進(jìn)度乘 2:

const _ = db.command
db.collection('todos').doc('todo-id').update({
  data: {
    progress: _.mul(2)
  }
})

db.command.push

更新指令,對一個(gè)值為數(shù)組的字段,往數(shù)組尾部添加一個(gè)或多個(gè)值?;蜃侄卧瓰榭?,則創(chuàng)建該字段并設(shè)數(shù)組為傳入值。

函數(shù)簽名:

function push(values: any[]): Command

示例代碼

const _ = db.command
db.collection('todos').doc('doc-id').update({
  data: {
    tags: _.push(['mini-program', 'cloud'])
  }
})

db.command.pop

更新指令,對一個(gè)值為數(shù)組的字段,將數(shù)組尾部元素刪除。

函數(shù)簽名:

function pop(values: any[]): Command

示例代碼

const _ = db.command
db.collection('todos').doc('doc-id').update({
  data: {
    tags: _.pop()
  }
})

db.command.shift

更新指令,對一個(gè)值為數(shù)組的字段,將數(shù)組頭部元素刪除。

函數(shù)簽名:

function shift(values: any[]): Command

示例代碼

const _ = db.command
db.collection('todos').doc('doc-id').update({
  data: {
    tags: _.shift()
  }
})

db.command.unshift

更新指令,對一個(gè)值為數(shù)組的字段,往數(shù)組頭部添加一個(gè)或多個(gè)值?;蜃侄卧瓰榭眨瑒t創(chuàng)建該字段并設(shè)數(shù)組為傳入值。

函數(shù)簽名:

function unshift(values: any[]): Command

示例代碼

const _ = db.command
db.collection('todos').doc('doc-id').update({
  data: {
    tags: _.unshift(['mini-program', 'cloud'])
  }
})
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)