Skip to main content

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 and Node.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

OperatorDescriptionExample
eqEqual to{age: _.eq(18)}
neqNot equal to{status: _.neq('deleted')}
gtGreater than{score: _.gt(80)}
gteGreater than or equal to{age: _.gte(18)}
ltLess than{price: _.lt(100)}
lteLess than or equal to{discount: _.lte(0.5)}
inIn an array{category: _.in(['tech', 'news'])}
ninNot in an array{status: _.nin(['deleted', 'banned'])}

🔍 Query Data

Single Record Query

Query the specified record by document ID.

Parameter Description

ParameterTypeRequiredDescription
docIdstring✅ RequiredThe 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

MethodParameter TypeRequiredDescription
where()object❌ NoQuery conditions, supporting operators
orderBy()string, string❌ NoSort field and direction ('asc' or 'desc')
limit()number❌ NoLimits the number of records returned. Default: 100 records, maximum: 1000 records.
skip()number❌ NoSkips the number of records, used for pagination
field()object❌ NoSpecifies 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

ParameterTypeRequiredDescription
dataobject✅ YesThe 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

ParameterTypeRequiredDescription
docIdstring✅ RequiredDocument ID to be updated
dataobject✅ YesThe 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

ParameterTypeRequiredDescription
whereobject✅ YesQuery conditions to identify the records to update
dataobject✅ YesThe 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

ParameterTypeRequiredDescription
docIdstring✅ RequiredDocument 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

ParameterTypeRequiredDescription
whereobject✅ YesQuery 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

NotesDescriptionRecommendations
Access ControlEnsure database security rules are properly configuredApply the principle of least privilege
Data ValidationPerform data validation on both client and server sidesPrevent invalid data from being stored
Performance OptimizationProperly use indexes and query conditionsAvoid 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