# Collection.count / Query.count
Calculates the number of records in the collection or number of result records corresponding to the query statement. Note that it is related to the setting of collection permission, and a user can only calculate the number of records that he/she has permission to read.
Function signature is shown as below:
function count(options?: object): Promise<Result>
Parameter description
options
is an optional parameter, an object with the following format. For example: if one of success
, fail
and complete
is passed in, it means the callback style is used, and Promise
is not returned.
Field | Type | Required | Default | Description |
---|---|---|---|---|
success | Function | No | Callback succeeds. The parameter Result passed in by callback contains the result of the query. The Result is defined as below. | |
fail | Function | No | Callback fails | |
complete | Function | No | Callback function when call completes (always executed whether call succeeds or fails) |
Description of return value
If the options
parameter is not passed, or the incoming options
parameter does not have a success
, fail
or complete
field, a Promise
will be returned or otherwise no value is returned. The results of resolve
and reject
for Promise
are defined as below:
Result Description | |
---|---|
resolve | The result of query. The Result is defined as below. |
reject | Reason for failure |
Result description
The result of success
callback and Result
of resolve
for Promise
are objects with the following structure:
Field | Type | Description |
---|---|---|
total | number | Number of results |
Sample code
Get total number of my to-dos
Callback style
const db = wx.cloud.database()
db.collection('todos').where({
_openid: 'xxx' // Enter the current user openid
}).count({
success: function(res) {
console.log(res.total)
}
})
Promise style
const db = wx.cloud.database()
db.collection('todos').where({
_openid: 'xxx' // Enter the current user openid
}).count().then(res => {
console.log(res.total)
})