Accessing CloudBase Data Models in WeChat Mini Program
Learn how to create CloudBase MySQL data models, add sample data, and query data from WeChat Mini Program.
1. Create a MySQL Data Model and Add Data
Note: You must log in to the CloudBase platform using the Tencent Cloud account associated with your WeChat Mini Program.
Create a data model named todos in the Cloud Development Platform, with the field information as follows:

| Field Name | Field Identifier | Data Type | Required | Unique |
|---|---|---|---|---|
| Completion Status | is_completed | Boolean | No | No |
| Description | description | Text, Multi-line text | No | No |
| Title | title | Text, Single-line text | No | No |
After creation, enter sample data in the todos data model.
2. Create a WeChat Mini Program

3. Install Cloud Development SDK Dependencies
- In the directory containing the mini-program's
app.json, run the command to install the npm package.
npm install @cloudbase/wx-cloud-client-sdk
- Click on the toolbar of the WeChat Developer Tools: "Tools" -> "Build npm".
4. Querying Data from the Mini-Program
- Initialize the SDK
// app.js
const { init } = require('@cloudbase/wx-cloud-client-sdk');
App({
onLaunch() {
let client = null;
this.globalData.getModels = async () => {
if (!client) {
wx.cloud.init({
env: env: '<CloudBase environment ID>',
});
client = init(wx.cloud);
}
return client.models;
};
},
globalData: {},
});
- Add the following query code in the page's
jsfile
// pages/index/index.js
Page({
data: {
todos: [],
},
onLoad() {
this.fetchTodos();
},
async fetchTodos() {
try {
const models = await getApp().globalData.getModels();
const { data } = await models.todos.list({
filter: {
where: {},
},
pageSize: 10,
pageNumber: 1,
getCount: true,
// envType: pre trial environment, prod production environment
envType: "prod",
});
this.setData({
todos: data.records,
});
} catch (error) {
console.error("Failed to obtain todo items:", error);
}
},
});
- Display the data in the corresponding page's
wxmlfile
<!--pages/index/index.wxml-->
<view>
<block wx:for="{{todos}}" wx:key="_id">
<text>{{item.title}}</text>
</block>
</view>
5. Run the Mini-Program
In the WeChat Developer Tools, click to compile and preview the Mini Program.
Notes
- Replace
<CloudBase environment ID>with your actual CloudBase environment ID.