Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

SDK database Collection request


May 20, 2021 WeChat Mini Program Development Document


Table of contents


Collection .get(): Promise<Object>

Support: small programs, cloud functions, web

Get collection data, or get collection data that is filtered based on query criteria.

Returns a value

Promise.<Object>

Property Type Description
data Array.<Object> An array of the results of a query, each element of the data is an Object, representing a record

Instructions for use

Count the number of collection records or the number of result records corresponding to the statistical query statement

The performance of the small terminal and the cloud function side will be as follows:

  • Small terminal: If no limit is specified, the default is up to 20 records.
  • Cloud function side: If no limit is specified, the default is up to 100 records.

If no skip is specified, it starts with the 0 record by default, and skip is often used for plying, as can be seen in the second sample code.

If you need to take all the data from the collection, you can refer to the cloud function to use the third sample code in the example only if the amount of data is small and in a cloud function

Example code 1

Get my to-do list:

Small terminal

const db = wx.cloud.database()
db.collection('todos').where({
  _openid: 'xxx' // 填入当前用户 openid
}).get().then(res => {
  console.log(res.data)
})

Cloud function side

const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
exports.main = async (event, context) => {
  return await db.collection('todos').where({
    _openid: 'xxx' // 填入当前用户 openid
  }).get()
}

Example code 2: Page the data

Get my second page to-do list, let's say 10 on a page, and now take page 2, you can specify skip 10 records

db.collection('todos')
  .where({
    _openid: 'xxx', // 填入当前用户 openid
  })
  .skip(10) // 跳过结果集中的前 10 条,从第 11 条开始返回
  .limit(10) // 限制返回数量为 10 条
  .get()
  .then(res => {
    console.log(res.data)
  })
  .catch(err => {
    console.error(err)
  })

Example code 3: Take all the data from the collection

Get all the to-do lists in the collection: Because there is a default limit of 100, it is likely that a request will not be able to take out all the data and will need to be taken in batches. Special attention: If the amount of non-data is very small, otherwise do not return all the data directly from the collection, one is to collect unnecessary data will cause performance problems, and the other is that the cloud function to return the size of the small program data will have a size limit

Cloud function side

const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const MAX_LIMIT = 100
exports.main = async (event, context) => {
  // 先取出集合记录总数
  const countResult = await db.collection('todos').count()
  const total = countResult.total
  // 计算需分几次取
  const batchTimes = Math.ceil(total / 100)
  // 承载所有读操作的 promise 的数组
  const tasks = []
  for (let i = 0; i < batchTimes; i++) {
    const promise = db.collection('todos').skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
    tasks.push(promise)
  }
  // 等待所有
  return (await Promise.all(tasks)).reduce((acc, cur) => {
    return {
      data: acc.data.concat(cur.data),
      errMsg: acc.errMsg,
    }
  })
}

The small terminal is compatible with Callback-style calls

As in the first example, the small terminal calls an equivalent Callback style call:

const db = wx.cloud.database()
db.collection('todos').where({
  _openid: 'xxx' // 填入当前用户 openid
}).get({
  success: function(res) {
    console.log(res.data)
  },
  fail: console.error
})

Collection.update(): Promise<Object>

Support side: Small program 2.9.4, cloud function, web

Update multiple records

Returns a value

Promise.<Object>

Property Type Description
stats Object Update the statistics for the results, which contain fields that see the definition of stats below

The structure of stats

Property Type Description
updated number The number of records that were successfully updated

Precautions

The success of an API call does not necessarily mean that the record you want to update has been updated, for example, it is possible that the specified where filter can only filter out 0 matching records, so you get a situation where the update API call was successful but no records were actually updated, as can be seen by stats.updated

The sample code

Update to-dos to add 10 to-do progress to all outstanding to-dos:

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

Collection.remove(): Promise<Object>

Support: Small program 2.9.4, cloud function

Delete multiple records. Note that skip and limit are only supported for deletion by matching where statements.

Returns a value

Promise.<Object>

Property Type Description
stats Object Update the statistics for the results, which contain fields that see the definition of stats below

The structure of stats

Property Type Description
removed number The number of records that were successfully deleted

Precautions

The success of an API call does not necessarily mean that the record you want to delete has been deleted, for example, it is possible to specify that the where filter can only filter out 0 matching records, so you get a situation where the update API call was successful but no records were actually deleted, as can be seen by stats.removed

The sample code

const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
exports.main = async (event, context) => {
  try {
    return await db.collection('todos').where({
      done: true
    }).remove()
  } catch(e) {
    console.error(e)
  }
}

Collection.count(): Promise<Object>

Support: small programs, cloud functions, web

Count the number of bars that match the query criteria

Returns a value

Promise.<Object>

Property Type Description
total number The number of results

Instructions for use

Count the number of collection records or the number of result records corresponding to the statistical query statement

The performance of the small terminal and the cloud function side will be as follows:

  • Small terminal: Note that regarding collection permission settings, a user can only count the number of records for which they have read permissions
  • Cloud function side: Because it belongs to the management side, you can count all the records in the collection

Small terminal sample code

Get the total number of my to-dos

Promise style

const db = wx.cloud.database()
db.collection('todos').where({
  _openid: 'xxx' // 填入当前用户 openid
}).count().then(res => {
  console.log(res.total)
})

Compatible with callback style

const db = wx.cloud.database()
db.collection('todos').where({
  _openid: 'xxx' // 填入当前用户 openid
}).count({
  success: function(res) {
    console.log(res.total)
  },
  fail: console.error
})

An example of the cloud function side

Get the total number of my to-dos

Promise style

const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
exports.main = async (event, context) => {
  return await db.collection('todos').where({
    _openid: 'xxx' // 填入当前用户 openid
  }).count()
}

Collection.add(options: Object): Promise<Object>

Support: small programs, cloud functions, web

New records, _id is automatically generated by the background if the incoming record object does not have an _id field, and _id cannot conflict with an existing record if _id is specified

Parameters

options: Object

Property Type The default Required Description
data Object Is The definition of the new record

Returns a value

Promise.<Object>

Property Type Description
_id string/number The new record _id

Small terminal sample code

Add a to-do list:

Promise style

db.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)
})
.catch(console.error)

Compatible with Callback style

db.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)
  },
  fail: console.error,
  complete: console.log
})

An example of the cloud function side

const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
exports.main = async (event, context) => {
  try {
    return await db.collection('todos').add({
      // data 字段表示需新增的 JSON 数据
      data: {
        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
      }
    })
  } catch(e) {
    console.error(e)
  }
}

Collection.watch(options: Object): Object

Support: Small program 2.8.1, Web

Listen for update events for data in the collection that meets the query criteria. Where, orderBy, limit, field is not supported when using watch.

Parameters

options: Object

Property Type The default Required Description
onChange function Is Successful callback, callback incoming parameter snapshot is a change snapshot, snapshot definition below
onError function Is Failed callback

Returns a value

Object

Watcher object

Property Type Description
close function Turn off listening, no parameters required, return Promise, and resolve when the shutdown resolve

Description of the parameters

Snapshot description

Field Type Description
docChanges ChangeEvent[] Update the array of events
docs object[] A snapshot of the data that represents the query results for the query statement after this update event
type string Snapshot type, with a value of init only the first time the data is initialized
Id number Change event id

ChangeEvent description

Field Type Description
Id number Update the event id
queueType string The list update type, which represents the impact of the update event on the listening list, enumeration values, as defined in QueueType
dataType string The data update type, which represents the specific update type of the record, enumeration values, and the definition can be found in DataType
docId string The updated record id
doc object The full record of the update
updatedFields object All updated fields and field updated values, key for the updated field path, value for field updated update during the update operation
removedFields string[] All deleted fields have this information update when the update operation occurs

QueueType enumeration values

Enumeration values Description
Init Initialize the list
update The record contents in the list are updated, but the records contained in the list remain unchanged
enqueue The record enters the list
dequeue Record the departure list

DataType enumeration values

Enumeration values Description
Init Initialize the data
update Record content updates for update
replace The record content is replaced for set action
add The record is new and corresponds add operation
remove The record is deleted, corresponding remove operation

Returns a description of the value

There is only one close method on the return value Watcher that can be used to turn off listening.

OrderBy and limit

From 2.9.2, orderBy and limit are supported for listening, and if the version number is not passed or version number is less than 2.9.2, the default is in descending order (equivalent to By order ('id', 'desc'), and the limit does not exist by default to take all the data.

Sample code: Listen according to query criteria

const db = wx.cloud.database()
const watcher = db.collection('todos')
  // 按 progress 降序
  .orderBy('progress', 'desc')
  // 取按 orderBy 排序之后的前 10 个
  .limit(10)
  // 筛选语句
  .where({
    // 填入当前用户 openid,或如果使用了安全规则,则 {openid} 即代表当前用户 openid
    _openid: '{openid}'
  })
  // 发起监听
  .watch({
    onChange: function(snapshot) {
      console.log('snapshot', snapshot)
    },
    onError: function(err) {
      console.error('the watch closed because of error', err)
    }
  })

Example code: Listen for changes in a record

const db = wx.cloud.database()
const watcher = db.collection('todos').doc('x').watch({
  onChange: function(snapshot) {
    console.log('snapshot', snapshot)
  },
  onError: function(err) {
    console.error('the watch closed because of error', err)
  }
})

Example code: Turn off listening

const db = wx.cloud.database()
const watcher = db.collection('todos').where({
  _openid: 'xxx' // 填入当前用户 openid
}).watch({
  onChange: function(snapshot) {
    console.log('snapshot', snapshot)
  },
  onError: function(err) {
    console.error('the watch closed because of error', err)
  }
})
// ...
// 关闭
await watcher.close()