CRUD
🔧 Initialize the SDK
Refer to the Initialize the SDK documentation to configure SDK initialization. After initialization, you will obtain the database instance db
and can start performing data operations.
This article applies to
Web SDK
andNode.js SDK
for CRUD operations. For Mini Program SDK operations, refer to Mini Program SDK Initialization
Query Operators
The database API provides various dynamical query operators such as greater than and less than, all exposed on the db.command
object.
📖 Detailed Documentation: wxCloud Database Operators
Operator | Description | Example |
---|---|---|
eq | Equal to | {age: _.eq(18)} |
neq | Not equal to | {status: _.neq('deleted')} |
gt | Greater than | {score: _.gt(80)} |
gte | Greater than or equal to | {age: _.gte(18)} |
lt | Less than | {price: _.lt(100)} |
lte | Less than or equal to | {discount: _.lte(0.5)} |
in | In an array | {category: _.in(['tech', 'news'])} |
nin | Not in an array | {status: _.nin(['deleted', 'banned'])} |
🔍 Query Data
Single Record Query
Query the specified record by document ID.
Parameter Description
Parameter | Type | Required | Description |
---|---|---|---|
docId | string | ✅ Required | The unique identifier of the document |
Code Sample
// Query a single record by document ID
const result = await db.collection('todos')
.doc('docId')
.get()
console.log('Query result:', result.data)
Response
{
data: [{
_id: "todo-id-123",
title: "Learn CloudBase",
completed: false,
// ... Other fields
}],
}
Batch Query
Query multiple records in a collection, supporting conditional filtering, sorting, pagination, etc.
Parameter Description
Method | Parameter Type | Required | Description |
---|---|---|---|
where() | object | ❌ No | Query conditions, supporting operators |
orderBy() | string, string | ❌ No | Sort field and direction ('asc' or 'desc') |
limit() | number | ❌ No | Limits the number of records returned. Default: 100 records, maximum: 1000 records. |
skip() | number | ❌ No | Skips the number of records, used for pagination |
field() | object | ❌ No | Specifies the fields to return, where true includes the field and false excludes it. |
// Query all records
const result = await db.collection('todos').get()
console.log('Query result:', result.data)
// Conditional query
const result = await db.collection('todos')
.where({
completed: false,
priority: 'high'
})
.get()
Advanced Query
const _ = db.command
// Complex conditional query
const result = await db.collection('todos')
.where({
// Age greater than 18
age: _.gt(18),
// Tag contains 'technology'
tags: _.in(['technology', 'learning']),
// Creation time within the last week
createdAt: _.gte(new Date(Date.now() - 7 * 24 * 60 * 60 * 1000))
})
.orderBy('createdAt', 'desc') // sorted by creation time in descending order
.limit(10) // limit 10
.skip(0) // skip 0 records (pagination)
.field({ // return only the specified fields
title: true,
completed: true,
createdAt: true
})
.get()
Pagination Query
// 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()
console.log(`Page ${pageNum} data:`, result.data)
Aggregation Query
// Statistical Query
const result = await db.collection('todos')
.aggregate()
.group({
_id: '$priority',
count: {
$sum: 1
}
})
.end()
console.log('Statistics by priority:', result.list)
➕ Add Data
Add Single Record
Add a new record to the collection.
Parameter Description
Parameter | Type | Required | Description |
---|---|---|---|
data | object | ✅ Yes | The data object to add |
Code Sample
// Add Single Record
const result = await db.collection('todos').add({
title: 'Learn CloudBase',
content: 'Completing Database Operations Tutorial',
completed: false,
priority: 'high',
createdAt: new Date(),
tags: ['learning', 'technology']
})
console.log('Successfully added, Document ID:', result._id)
📝 Update Data
Update Single Record
Update the specified record by document ID.
Parameter Description
Parameter | Type | Required | Description |
---|---|---|---|
docId | string | ✅ Required | Document ID to be updated |
data | object | ✅ Yes | The data object to update |
Code Sample
// Update the specified document
const result = await db.collection('todos')
.doc('todo-id')
.update({
title: 'Learn CloudBase Database',
completed: true,
updatedAt: new Date(),
completedBy: 'user123'
})
console.log('Updated successfully, Affected records:', result.stats.updated)
Batch Updating
Batch update multiple records based on query conditions.
Parameter Description
Parameter | Type | Required | Description |
---|---|---|---|
where | object | ✅ Yes | Query conditions to identify the records to update |
data | object | ✅ Yes | The data object to update |
Code Sample
// Batch update multiple records
const batchResult = await db.collection('todos')
.where({
completed: false,
priority: 'low'
})
.update({
priority: 'normal',
updatedAt: new Date()
})
console.log('Batch update result:', batchResult)
Update or Create
Update the document, or create it if it does not exist
const setResult = await db.collection('todos')
.doc("doc-id")
.set({
completed: false,
priority: 'low'
})
🗑️ Delete Data
Delete Single
Delete the specified record by document ID.
Parameter Description
Parameter | Type | Required | Description |
---|---|---|---|
docId | string | ✅ Required | Document ID to be deleted |
Code Sample
// Delete the specified document
const result = await db.collection('todos')
.doc('todo-id')
.remove()
console.log('Deleted successfully, Affected records:', result.stats.removed)
Batch Delete
Batch delete multiple records based on query conditions.
Parameter Description
Parameter | Type | Required | Description |
---|---|---|---|
where | object | ✅ Yes | Query conditions to identify the records to delete |
Code Sample
// Batch delete multiple records
const _ = db.command
const batchResult = await db.collection('todos')
.where({
completed: true,
createdAt: _.lt(new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)) // 30 days ago
})
.remove()
console.log('Batch deletion result:', batchResult)
⚠️ Important Notes
Error Handling
All database operations should use try-catch for error handling:
try {
const result = await db.collection('todos').get()
console.log('Query succeeded:', result.data)
} catch (error) {
console.error('Query failed:', error)
}
Important Reminder
Notes | Description | Recommendations |
---|---|---|
Access Control | Ensure database security rules are properly configured | Apply the principle of least privilege |
Data Validation | Perform data validation on both client and server sides | Prevent invalid data from being stored |
Performance Optimization | Properly use indexes and query conditions | Avoid full table scans |
💡 Best Practices
Data Structure Design
- Design collection structures properly: Avoid excessive nesting and maintain clear data structures
- Create Indexes: Create indexes for commonly queried fields to improve performance.
- Data Type: Use appropriate data types, such as timestamps for dates
Query Optimization
- Limit Returned Data: Use
limit()
to control the number of returned records - Field Projection: Use
field()
to return only the required fields
Security Considerations
- Security Rules: Configure appropriate database security rules
- Input Validation: Validate the legitimacy of user input data
- Sensitive Information: Avoid storing sensitive information on the client side