Overview
What is a Data Model?
The data model is a declarative data management solution provided by cloud development, built on top of the cloud development database, offering developers a more efficient and secure way to operate data.
Simply put, the data model is like a customized "smart butler" for your data:
- 📋 Define Data Structures: Define the fields, types, and relationships of data through the visual interface
- 🛡️ Automatic Data Validation: Ensuring data accuracy and consistency
- 🔗 Handle Relationships: Automatically manage complex relationships between data
- 🚀 Includes Multi-platform SDKs: Define once, use across multiple platforms (Mini Programs, Web, Cloud Functions)
- 🎛️ Built-in Management Interface: Provides an out-of-the-box data management backend
- 🤖 AI Intelligent Analysis: Leverage AI to uncover data value
💡 Core Philosophy: Enable developers to focus on business logic rather than the complexity of underlying data operations.
Core Features Overview
Feature | Description | Value |
---|---|---|
🔍 Intelligent Data Validation | Automatically checks data types and formats to prevent erroneous data from entering the database | Improves data quality and reduces bugs |
🔗 Relationship Management | Automatically handles one-to-one, one-to-many, and many-to-many relationships | Simplifies complex queries and boosts development efficiency |
⚡ Includes Multi-platform SDKs | Define once, automatically generates SDKs for Mini Programs/Web/Cloud Functions | Unifies development experience and reduces repetitive work |
🎛️ Visual Management | Built-in CMS admin interface supporting non-technical staff operations | Reduces operational costs and enhances collaboration efficiency |
🏗️ Low-code Application Generation | One-click generation of customizable admin console applications | Rapid delivery, shortens development cycles |
🤖 AI Data Analysis | Intelligently analyzes data trends and patterns | Enables data-driven decisions and uncovers business value |
🚀 Advanced Query Capabilities | Supports complex conditional queries, aggregation analysis, and more | Meets diverse business needs |
Relationship Between Data Models and Databases
A data model is a representation of a database, defining the structure, fields, constraints, and relationships of the data. It provides a unified approach to describe and manipulate data, simplifying data operations and queries. The capability of data models essentially constitutes Object-Relational Mapping (ORM), commonly used in development.
The data model and database have an association relationship. A data model corresponds to a collection (in a non-structured database) or a table (in a structured database) in the database.
Using data models does not mean being restricted to using data models only. While using data models, if you need more complex operations or operations that data models cannot handle well, you can also use the database's native methods to directly read and write data.
Compared to ORM in traditional development frameworks, the Cloud Development data model not only includes ORM-related SDK capabilities for data operations, but also integrates additional features such as a data management interface, user and permission systems, content management, and further capabilities like data model-based application generation and data analysis. For more advantages, see "Why Use Data Models".
How to Get Started with Data Models?
🚀 Quick Start
- Access the console: Go to the CloudBase console
- Select database: Switch to Database/Document-based
- Create model: Click "New Model", then select a creation method
📋 Creation Methods
Method | Applicable Scenarios | Description |
---|---|---|
🆕 Add Model | New project development | Create a new data model from scratch |
📦 Import Legacy CMS | Project migration | Import models from the existing CloudBase CMS to enjoy the functional upgrades of the new version |
✅ Creation Complete
After creating a new model, you can immediately utilize the powerful capabilities provided by the data model!
💡 Tip: It is recommended to read the Quick Start tutorial to get started quickly with practical examples.
Why Choose Data Models?
Data models deliver a comprehensive enhancement in development experience for developers:
- 🚀 Improve Development Efficiency: Automatically generate SDKs to reduce repetitive coding
- 💰 Reduce Maintenance Costs: Unified data management minimizes Ops workload
- 🛡️ Enhanced Data Security: Built-in permission control and data validation mechanisms
- 📊 Enhanced Data Analysis: AI intelligent analysis to uncover data value
- 🎯 Simplify Team Collaboration: Visual management interface accessible to both technical and non-technical staff
🛡️ Intelligent Data Validation and Type Checking
Data models provide an automated data validation mechanism, performing strict type checking and format validation before data is stored, ensuring data accuracy and consistency, and preventing data quality issues at the source.
📝 Live Demo
Suppose we have defined an article model post
with the following fields:
title
(string type) - Article titlebody
(string type) - Article content
Now we intentionally pass data of the wrong type to test the validation mechanism:
try {
const { data } = await models.post.create({
data: {
title: "Hello, world👋",
body: 123456, // ❌ Intentionally passed numeric type, expected string type
},
});
console.log("Created successfully:", data);
} catch (error) {
console.error("Verification failed:", error);
}
🚨 Validation Result
When we attempt to insert data of the wrong type, the data model immediately detects the issue and blocks the operation:
Error: WxCloudSDKError: [Error] Data format validation failed. Root cause: [#/body: expected type: String, found: Integer]. Reason: field [Content], identifier [body], type mismatch: expected type: string. Resolution steps: Please correct the data type according to the reason. errRecord:{"title":"Hello, world👋","body":123456} [Operation] Calling post.create
✅ Validation Benefits
- 🔍 Precise Localization: Accurately identifies which field has what issue
- 📝 Friendly Tips: Provide clear error reasons and resolution suggestions
- 🛡️ Data Protection: Prevent dirty data from entering the database
- 🐛 Reduce Bugs: Catch data type issues during the development phase
🔗 Intelligent Relationship Handling
The data model can automatically handle complex data relationships, supporting various relationship types such as one-to-one, one-to-many, and many-to-many. Without the need to manually write complex JOIN queries, the system automatically processes the association logic between data.
🎯 Query Association Example
Taking the relationship between articles and comments as an example, we can easily implement cross-model data queries. Using the select
parameter allows precise control over the returned fields and associated data:
const { data } = await models.post.list({
// Precisely control returned fields to optimize query performance
select: {
_id: true,
title: true,
updatedAt: true,
// Join query for comment data
comments: {
_id: true,
createdAt: true,
comment: true,
},
},
filter: {
where: {}, // Query conditions
},
getCount: true, // Get total count
});
console.log("Query result:", data);
📊 Response Data
The system automatically handles relationships and returns structured data:
{
"records": [
{
"_id": "9FSAHWM9VV",
"title": "Bonjour le Monde👋",
"updatedAt": 1718096503886,
"comments": [
{
"_id": "9FSAJF3GLG",
"createdAt": 1718096509916,
"comment": "This is a comment"
}
]
},
{
"_id": "9FSAHWM9VU",
"title": "Hello, world👋",
"updatedAt": 1718096503886,
"comments": [] // No comments yet
}
],
"total": 2
}
✨ Benefits of Association Queries
- 🚀 Performance Optimization: Return only the required fields to reduce data transfer.
- 🔄 Automatic Association: No need to manually write complex JOIN statements.
- 📱 Multi-level Nesting: Supports deep-level associated data queries.
- 🎯 Precise Control: Flexibly specify the returned fields for each associated object
⚡ Automatic Generation of Multi-platform SDKs
The cloud development platform provides multi-platform SDKs, supporting various platforms including Mini Programs, Web, and Cloud Functions. Define once, reuse across multiple platforms, significantly improving development efficiency.
🔄 Intelligent Upsert Operation
Take the upsert() method as an example; it intelligently determines whether to create a new record or update an existing one:
const postData = {
title: "Hello World",
body: "This is an example article",
_id: "hello-world-post",
};
const { data } = await models.post.upsert({
create: postData, // Create if not exists
update: postData, // Update if exists
filter: {
where: {
_id: { $eq: postData._id }
},
},
});
console.log("Operation result:", data);
📊 Response Data Description
// 🆕 When creating a new record
{
"count": 0, // The number of updated records is 0
"id": "hello-world-post" // ID of the newly created record
}
// 🔄 When updating existing records
{
"count": 1, // The number of updated records is 1
"id": "" // ID is not returned for update operations
}
🎯 Advantages of Multi-platform SDKs
- 📱 Unified interface: All platforms use the same API invocation method
- 🔒 Type safety: TypeScript support, catch errors at compile time
- ⚡ Automatic optimization: Automatically optimizes performance based on platform characteristics.
- 🔄 Real-time synchronization: SDK automatically updates after model changes
🎛️ Built-in Data Management System
The data model provides an out-of-the-box content management system (CMS), enabling non-technical personnel to easily perform data management and maintenance, significantly reducing operational costs.
✨ Core Features
- 📝 Visual Editing: Intuitive form interface, no programming knowledge required
- 👥 Permission Management: Fine-grained user permission control
- 📊 Data Statistics: Built-in data analysis and reporting features
- 🔍 Advanced Search: Supports multi-condition filtering and sorting
- 📱 Responsive Design: Supports desktop and mobile access
📚 Learn more: See * 🎛️ Use Data Management to explore the full features
🏗️ Low-code Application Generator
The data model supports one-click generation of complete admin backend applications, utilizing advanced low-code technology to enable visual modification and custom development, allowing you to avoid building management interfaces from scratch.
🎨 Low-Code Features
- 🖱️ Drag-and-drop Design: Quickly build interfaces through dragging components
- 🎯 Rich Templates: Provides multiple pre-built templates and components
- 🔧 Deep Customization: Supports custom styles and business logic
- 📦 One-Click Deployment: Generated applications can be deployed and used directly
- 🔄 Real-time Preview: A WYSIWYG development experience
🤖 AI Intelligent Data Analysis
The data model integrates a powerful AI analytics engine that automatically uncovers patterns and trends in data, delivering intelligent support for business decision-making.
🧠 AI Analytical Capabilities
- 📈 Trend Forecasting: Predicts future trends based on historical data
- 🔍 Anomaly Detection: Automatically identifies anomalous patterns in data
- 📊 Intelligent Reports: Automatically generates visualized analysis reports
- 💡 Insights and Recommendations: Provides data-driven business suggestions
- 🎯 User Profiling: Intelligently analyzes user behavior characteristics
🚀 Value Proposition: Extracts valuable business insights from massive data to truly drive business growth
🚀 Advanced Database Query Support
Data models support native SQL queries and are compatible with advanced querying capabilities of relational databases like MySQL. When model APIs cannot meet complex query requirements, you can directly use SQL statements for precise control.
💪 Advanced Query Capabilities
- 🔍 Complex Condition Filtering: Supports multi-table join queries, subqueries, and more
- 📊 Aggregation Analysis: GROUP BY, HAVING, aggregate functions, etc.
- ⚡ Performance Optimization: Index optimization, query plan analysis
- 🔒 Security Protection: Parameterized queries to prevent SQL injection
📝 Real-world Cases
Query records where the author's contact phone number starts with "1858":
const result = await models.$runSQL(
"SELECT * FROM `article_table` WHERE author_tel LIKE '{{tel}}';",
{
tel: "1858%", // Parameterized query, secure and reliable
}
);
console.log("Query result:", result);
📊 Response Data
{
"data": {
"total": 1,
"executeResultList": [
{
"_id": "9JXU7BWFZJ",
"title": "Example Article",
"author_tel": "18588881111",
"createdAt": 1719475245475,
"region": "Beijing"
// ... Other fields
}
],
"backendExecute": "28"
},
"requestId": "0d4c98c3-a3ff-4c55-93cc-d0f5c835f82c"
}
📚 Further Learning: See Database Raw Query Documentation to learn more advanced usage
🎯 Summary
The cloud development data model provides a comprehensive data management solution for modern application development:
- 🏗️ Architectural Advantages: Based on cloud-native architecture, stable and reliable
- 🚀 Development Efficiency: Automatically generate SDKs to reduce repetitive work
- 🛡️ Data Security: Built-in validation and permission control mechanisms
- 🎛️ Easy Management: Visual management interface reduces operational costs
- 🤖 Intelligent Analysis: AI-driven data insights capabilities
- 🔧 Flexible Scalability: Supports raw queries and custom logic
Start your data model journey now! 👉 Quick Start tutorial