# Collection.get / Query.get
Obtains a collection of data, or a collection of data filtered based on the query criteria.
If limit is not specified, a maximum of 20 records are returned.
If skip is not specified, the records are returned from the record 0, and skip is generally used for paging. Refer to Sample code 2.
If you need to get all the collection data, see the third sample code.
Function signature is shown as below:
function get(): Promise<Result>
Description of return value
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
Result
from Promise
resolve
is an object with the following structure:
Field | Type | Description |
---|---|---|
data | Array | The result array of a query. Each element of data is an Object representing a record. |
Sample code 1
Get my to-do list
Promise style
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
exports.main = async (event, context) => {
return await db.collection('todos').where({
_openid: 'xxx' // Enter the current user openid
}).get()
}
Sample code 2: Get data by paging
To get your to-do list on page 2, if, for example, there are ten to-dos on page 1, and you can specify to skip 10 to-dos.
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
exports.main = async (event, context) => {
return await db.collection('todos')
.where({
_openid: 'xxx', // Enter the current user openid
})
.skip(10) // The first 10 to-dos in the result set are skipped, and results are returned from the 11th one onwards.
.limit(10) // A maximum of 10 results are returned.
.get()
}
Sample code 3: Get all the collection data
Get the to-do list in a collection: Only limit
100 items are allowed in a list by default, so you might not be able to get all the data in one request. Get in batch as needed.
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const MAX_LIMIT = 100
exports.main = async (event, context) => {
// Get the total number of the collection records first
const countResult = await db.collection('todos').count()
const total = countResult.total
// Calculate in how many times you can get it
const batchTimes = Math.ceil(total / 100)
// Carry all the promise arrays with read
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)
}
// Wait all
return (await Promise.all(tasks)).reduce((acc, cur) => {
return {
data: acc.data.concat(cur.data),
errMsg: acc.errMsg,
}
})
}