当前位置:网站首页>Wechat applet cloud development 1 - Database
Wechat applet cloud development 1 - Database
2022-07-19 11:38:00 【cs_ upupo】
There are two most important aspects of wechat applet cloud development :
1、 Cloud database ;
2、 Cloud functions ;
Learning these two points can basically carry out the cloud development of wechat applet ;
First , Let's first look at the basic operation of wechat applet cloud database :
1) Open micro Letter developer tools , Create a cloud development wechat applet , Check use cloud development when creating a project ;( Be careful : Using cloud development requires appId, Cannot use test number , Users who use cloud development for the first time need to open the cloud development function )
2) Click the cloud development option in the menu bar , Enter the cloud development control panel , Create a new development environment , Then click database , Create a new collection in the database of the current environment lists:

Then click the data permission root in the database to configure the required database permissions ;
Detailed permissions visible : Access control | Wechat open documents
3) In the project app.js Do the following configuration in :
// app.js
App({
onLaunch: function () {
if (!wx.cloud) {
console.error(' Please use 2.2.3 Or more base libraries to use cloud capabilities ');
} else {
wx.cloud.init({
// env Parameter description :
// env Parameters determine the next cloud development call initiated by the applet (wx.cloud.xxx) Which cloud environment resources will be requested by default
// Please fill in the environment here ID, Environmental Science ID You can open the cloud console to view
// If not, the default environment will be used ( First environment created )
env: ' The environment of the required development environment ID',
traceUser: true,
});
}
this.globalData = {};
}
});Environmental Science ID In this place :

4) Initialization, addition, deletion, modification and query of cloud database :
Take the above database lists Set as an example :
// Initialize database
const db = wx.cloud.database();
// obtain In the database lists aggregate
const lists=db.collection('lists');Insert :
db.collection(' Collection name ').add({
data:{
// data The field indicates the JSON data
}
}).then(res=>{console.log(res))Throw out the following information, that is, the addition is successful :

Delete :
db.collection(' Collection name ').doc(' To delete a field _id').remove().then(res=>{})The deletion is successful when the following information is thrown :

to update :
db.collection(' Collection name ').doc(' The data that needs to be changed _id').update({
// data Pass in data that needs to be locally updated
data: {
}
}).then(res=>{})
eg:
const _ = db.command
db.collection('lists').doc('0ab5303b6286010904a878280d163117').update({
data: {
// Indicates that the database will age Field auto increment 1
age: _.inc(1)
},
success: function(res) {
console.log(res.data)
}
})The following information is thrown to indicate that the update is successful :

Inquire about :
Query the data of a record :
db.collection(' Collection name ').doc(' Of the data _id').get().then(res => {
// res.data Data containing the record
console.log(res.data)
})Query... According to the conditions :
db.collection(' Collection name ').where({
// Query criteria Such as :
age:18
}).get().then(res => {
// res.data contain age by 18 All data for
console.log(res.data)
})Query sets all data :
If you want to get the data of a collection , Like getting todos All records on the collection , You can call... On a collection get Method to get , But this is not usually recommended , In small programs, we need to try to avoid getting too much data at one time , Only necessary data should be obtained . In order to prevent misoperation and protect the applet experience , When the applet side obtains the collection data, the server defaults once and returns at most 20 Bar record , The number of cloud function end is 100. Developers can use limit Method to specify the number of records to get , But the applet side cannot exceed 20 strip , The cloud function end cannot exceed 100 strip .
db.collection(' Collection name ').get().then(res => {
// res.data Is a data that contains all records in the collection that have permission to access , No more than 20 strip
console.log(res.data)
})The following is an example of getting a collection of all records on the cloud function side , Because at most one time 100 Restrictions on , Therefore, it is likely that one request cannot fetch all the data , It is necessary to take... In batches :
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const MAX_LIMIT = 100
exports.main = async (event, context) => {
// First, take out the total number of collection records
const countResult = await db.collection(' Collection name ').count()
const total = countResult.total
// The calculation needs to be divided into several times
const batchTimes = Math.ceil(total / 100)
// Carrying all read operations promise Array of
const tasks = []
for (let i = 0; i < batchTimes; i++) {
const promise = db.collection(' Collection name ').skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
tasks.push(promise)
}
// Wait for all
return (await Promise.all(tasks)).reduce((acc, cur) => {
return {
data: acc.data.concat(cur.data),
errMsg: acc.errMsg,
}
})
}View more database manipulation statements : initialization | Wechat open documents
more API see : Wechat open documents
边栏推荐
- 565. 数组嵌套 : 常规模拟题
- Conversion of unity3d model center point (source code)
- TiKV Follower Read
- At5147-[agc036d]negative cycle [DP, model conversion]
- 03-1、内联函数、auto关键字、typeid、nullptr
- Un modèle de détection par défaut basé sur le réseau neuronal évolutif rapide dans le contrôle de la qualité des produits - lire les notes
- Developing those things: how to solve the problem of long-time encoding and decoding of RK chip video processing?
- Mysql索引的类型(单列索引、组合索引 btree索引 聚簇索引等)
- 性能优化之@Contended减少伪共享
- TiDB 内存控制文档
猜你喜欢

STC8H开发(十四): I2C驱动RX8025T高精度实时时钟芯片

华为无线设备配置频谱导航

MySQL autoincrement ID, UUID and snowflake ID

Delegate parents and other loaders

要想组建敏捷团队,这些方法不可少

To build agile teams, these methods are indispensable

Daily question brushing record (26)

LeetCode 558. Intersection of quadtree

XSS. haozi. Me brush questions
![[multithreading] detailed explanation of JUC (callable interface, renntrantlock, semaphore, countdownlatch), thread safe set interview questions](/img/3a/b0bdf66e11e66234a222d977fd933c.png)
[multithreading] detailed explanation of JUC (callable interface, renntrantlock, semaphore, countdownlatch), thread safe set interview questions
随机推荐
Synchronized lock upgrade
Learning note 3 -- basic idea of machine learning in planning control
Leetcode 1304. 和为零的 N 个不同整数
Introduction to common distributed locks
Download of common getshell tools
At5147-[agc036d]negative cycle [DP, model conversion]
【嵌入式单元测试】C语言单元测试框架搭建
Ppde Q2 welcome | welcome 22 AI developers to join the propeller developer technical expert program!
TCP拥塞控制详解 | 7. 超越TCP
Codeforces - 587e (linear basis + segment tree + difference)
A current List of AWESOME Qt and qml
The type of MySQL index (single column index, combined index, BTREE index, clustered index, etc.)
微服务上线规范
02-3. Difference between pointer and reference
Loj#2324-「清华集训 2017」小 Y 和二叉树
Mpu9250 ky9250 attitude, angle module and mpu9250 MPL DMA comparison
The concept of data guard broker and the configuration process of data guard broker
Tire Defect Detection Using Fully Convolutional Network-论文阅读笔记
Keras深度学习实战(14)——从零开始实现R-CNN目标检测
Powercli script performance optimization