当前位置:网站首页>微信小程序云开发 1 - 数据库
微信小程序云开发 1 - 数据库
2022-07-17 12:06:00 【cs_upupo】
微信小程序云开发最重要的有两点:
1、云数据库;
2、云函数;
学会这两点基本就能够进行微信小程序的云开发;
首先,我们先看微信小程序云数据库的基本操作:
1)打开微 信开发者工具,创建一个云开发微信小程序,在创建项目时勾选使用云开发即可;(注意:使用云开发需要使用appId,不能使用测试号,第一次使用云开发的用户需要去开通云开发功能)
2)点击菜单栏的云开发选项,进入云开发控制面板,创建一个新的开发环境,然后点击数据库,在当前环境的数据库中创建一个新的集合lists:

然后点击数据库中的数据权限根配置自己所需的数据库权限;
详细权限可见:权限控制 | 微信开放文档
3)在项目app.js中做如下配置:
// app.js
App({
onLaunch: function () {
if (!wx.cloud) {
console.error('请使用 2.2.3 或以上的基础库以使用云能力');
} else {
wx.cloud.init({
// env 参数说明:
// env 参数决定接下来小程序发起的云开发调用(wx.cloud.xxx)会默认请求到哪个云环境的资源
// 此处请填入环境 ID, 环境 ID 可打开云控制台查看
// 如不填则使用默认环境(第一个创建的环境)
env: '所需开发环境的环境ID',
traceUser: true,
});
}
this.globalData = {};
}
});环境ID在这个地方:

4)云数据库的初始化及增删改查:
以如上数据库lists集合为例:
// 初始化数据库
const db = wx.cloud.database();
// 获取 数据库中lists集合
const lists=db.collection('lists');插入:
db.collection('集合名称').add({
data:{
// data 字段表示需新增的 JSON 数据
}
}).then(res=>{console.log(res))抛出如下信息即为添加成功:

删除:
db.collection('集合名称').doc('要删除字段的_id').remove().then(res=>{})抛出如下信息即为删除成功:

更新:
db.collection('集合名称').doc('需要更改的那条数据的_id').update({
// data 传入需要局部更新的数据
data: {
}
}).then(res=>{})
eg:
const _ = db.command
db.collection('lists').doc('0ab5303b6286010904a878280d163117').update({
data: {
// 表示指示数据库将age字段自增 1
age: _.inc(1)
},
success: function(res) {
console.log(res.data)
}
})抛出如下信息即为更新成功:

查询:
查询一条记录的数据:
db.collection('集合名称').doc('该条数据的_id').get().then(res => {
// res.data 包含该记录的数据
console.log(res.data)
})根据条件查询:
db.collection('集合名称').where({
// 查询条件 如:
age:18
}).get().then(res => {
// res.data 包含age为18的所有数据
console.log(res.data)
})查询集合所有数据:
如果要获取一个集合的数据,比如获取 todos 集合上的所有记录,可以在集合上调用 get 方法获取,但通常不建议这么使用,在小程序中我们需要尽量避免一次性获取过量的数据,只应获取必要的数据。为了防止误操作以及保护小程序体验,小程序端在获取集合数据时服务器一次默认并且最多返回 20 条记录,云函数端这个数字则是 100。开发者可以通过 limit 方法指定需要获取的记录数量,但小程序端不能超过 20 条,云函数端不能超过 100 条。
db.collection('集合名称').get().then(res => {
// res.data 是一个包含集合中有权限访问的所有记录的数据,不超过 20 条
console.log(res.data)
})下面是在云函数端获取一个集合所有记录的例子,因为有最多一次取 100 条的限制,因此很可能一个请求无法取出所有数据,需要分批次取:
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const MAX_LIMIT = 100
exports.main = async (event, context) => {
// 先取出集合记录总数
const countResult = await db.collection('集合名称').count()
const total = countResult.total
// 计算需分几次取
const batchTimes = Math.ceil(total / 100)
// 承载所有读操作的 promise 的数组
const tasks = []
for (let i = 0; i < batchTimes; i++) {
const promise = db.collection('集合名称').skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
tasks.push(promise)
}
// 等待所有
return (await Promise.all(tasks)).reduce((acc, cur) => {
return {
data: acc.data.concat(cur.data),
errMsg: acc.errMsg,
}
})
}更多数据库操纵语句查看:初始化 | 微信开放文档
更多API查看:微信开放文档
边栏推荐
- Simulation Research on optimal detection of fault data in communication network
- C语言之构造类型细讲
- Secondary vocational network security - (2022 network security NC batch connection script) free script oh~~~
- Go to school = earn money? Immortal college without paying tuition fees!
- HCIA 静态基础实验 7.8
- HCIA 静态综合实验报告 7.10
- Microsoft OneNote 教程,如何在 OneNote 中插入数学公式?
- 中科磐云—D模块web远程代码执行漏洞解析
- HCIA RIP实验 7.11
- 【原创】Magisk+Shamiko过APP ROOT检测
猜你喜欢

Let, const, VaR in ES6

HCIA 静态综合实验报告 7.10

Huawei Shengsi mindspire detailed tutorial
![[Download] take you to use FRP to achieve intranet penetration detailed tutorial!](/img/8c/f3a5dd05966bcb98f24d97e1576a7e.png)
[Download] take you to use FRP to achieve intranet penetration detailed tutorial!

Machine learning basics that can be easily introduced in 5 minutes

HCIA RIP实验 7.11
![[Northeast Normal University] information sharing of postgraduate entrance examination and re examination](/img/a8/41e62a7a8d0a2e901e06c751c30291.jpg)
[Northeast Normal University] information sharing of postgraduate entrance examination and re examination

C语言之构造类型细讲

【附下载】带你使用frp实现内网穿透详细教程!

Huawei wireless device configuration intelligent roaming
随机推荐
【微信小程序】使出千手浮图—回滚式
SSH連接華為ModelArts notebook
B. AccurateLee【双指针】【substr函数】
Run yolov3 on Huawei modelarts_ coco_ detection_ dynamic_ AIPP sample
高效理解 FreeSql WhereDynamicFilter,深入了解设计初衷[.NET ORM]
[200 opencv routines] 233 Moment invariants of regional features
卫星网络中基于时变图的节能资源分配策略
A multidimensional sequence anomaly detection method based on Grubbs and isolated forest
Simulation Research on optimal detection of fault data in communication network
如何解决谷歌浏览器解决跨域访问的问题
[sort] merge sort
华为昇思MindSpore详细教程
Story of status code
Construction practice of pipeline engine of engineering efficiency ci/cd
The module created by yourself uses CMD to open the report modulenotfounderror: no module named solution
Complete knapsack problem code template
2022年陕西省中职组“网络空间安全”—数据包分析
【分离式超图像分类平台】使用深度学习中那些令人兴奋的模型搭建图像分类平台
Good news
高性能IO框架库libevent(三):libevent框架函数概述