# db.command.set

Update command. Sets the value of a field to be equal to the specified value.

Function signature:

function set(value: any): Command

Compared with the method in which pure JS objects are imported, this method has an advantage of specifying the value of a field to be equal to one object:

const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
exports.main = async (event, context) => {
  try {
    // In the following method, only the style.color is updated to red, and the style is not updated to { color: 'red' }, without affecting other fields in the style.
    const res1 = await db.collection('todos').doc('doc-id').update({
      data: {
        style: {
          color: 'red'
        }
      }
    })

    // In the following method, the style is updated to { 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)
  }
}
点击咨询小助手