Skip to main content

Fetch Data

Initialize the SDK​

import cloudbase from "@cloudbase/node-sdk";

const app = cloudbase.init({
env: "your-env-id", // Replace with your environment id
});

const db = app.database();
const _ = db.command; // Obtain the query command

Querying a Single Record​

Query the specified record via document ID.

db.collection(collectionName).doc(docId).get()
  • collectionName: collection name
  • docId: document ID

Parameter Description​

ParameterTypeRequiredDescription
docIdstringRequiredUnique identifier of the document

Code Example​

// Query a single record via document ID
const result = await db.collection('todos')
.doc('docId')
.get()

Response​

{
data: [{
_id: "todo-id-123",
title: "Learn CloudBase",
completed: false,
// ... other fields
}],
}

Querying Multiple Records​

Querying multiple records in a collection supports conditional filtering, sorting, pagination, and more.

db.collection(collectionName).where(conditions).get()
  • collectionName: collection name
  • conditions: query conditions (optional)

⚠️ Note: The get() method returns 100 records by default. If you need more data, please use pagination.

Parameter Description​

MethodParameter TypeRequiredDescription
where()objectNoQuery condition that supports operators
orderBy()string, stringNoSort field and direction ('asc' or 'desc')
limit()numberNoMaximum number of records to return (default: 100, max: 1000)
skip()numberNoNumber of records to skip for pagination
field()objectNoSpecifies the fields to return (true: return, false: exclude)
// Query all records
const result = await db.collection('todos').get()

// Conditional query
const result = await db.collection('todos')
.where({
completed: false,
priority: 'high'
})
.get()

Complex Queries​

const _ = db.command

// Complex conditional query
const result = await db.collection('todos')
.where({
// Age is greater than 18
age: _.gt(18),
// tag contains 'technology'
tags: _.in(['Technology', 'Learning']),
// Creation time is within the last week
createdAt: _.gte(new Date(Date.now() - 7 * 24 * 60 * 60 * 1000))
})
.orderBy('createdAt', 'desc') // Sort by creation time in descending order
.limit(10) // Limit to 10 records
.skip(0) // Skip 0 records (pagination)
.field({ // Return only specified fields
title: true,
completed: true,
createdAt: true
})
.get()

Pagination Queries​

// Pagination Query Example
const pageSize = 10
const pageNum = 1

const result = await db.collection('todos')
.orderBy('createdAt', 'desc')
.skip((pageNum - 1) * pageSize)
.limit(pageSize)
.get()

Aggregate Queries​

For aggregation syntax, refer to Aggregate Queries

// Statistical Query
const result = await db.collection('todos')
.aggregate()
.group({
_id: '$priority',
count: {
$sum: 1
}
})
.end()

console.log('Statistics by priority:', result.list)

Geographic Location Query​

⚠️ Note: When querying geographic location fields, please create a geographic location index; otherwise, the query will fail.

const _ = db.command
// Query nearby users (sorted by distance)
db.collection("users").where({
location: _.geoNear({
geometry: new db.Geo.Point(116.404, 39.915), // Tiananmen coordinates
maxDistance: 1000, // Maximum distance 1000 meters
minDistance: 0 // Minimum distance 0 meters
})
}).get()

// Query users within a specified area
db.collection("users").where({
location: _.geoWithin({
geometry: polygon // Use the polygon defined above
})
}).get()

// Query users intersecting with the path
db.collection("users").where({
location: _.geoIntersects({
geometry: line // Use the line defined above
})
}).get()