- # 使用小程序云开发API更新数组中的单个数组元素
使用小程序云开发API更新数组中的单个数组元素 看了看mongoDB的更新数据方式,找到了解决办法,解决方法如下,亲测可用: 第一种方法:使用位置操作符$ [代码]代码,条件更新写在云函数中 [代码] [图片] [代码]test_api集合原始数据如下 [代码] [图片] [代码]在云函数中执行1中的代码,数组users中id为1001的用户添加了一个新的属性test [代码] [图片] [代码]原理分析 [代码] where条件是查找数组中id属性为1001的用户 update中的使用’users.$.test’: ‘test’ 注意里面的$符号,在mongoDB中,这个符号叫做位置操作符,代表数组的下标,如下引自《mongoDB实战》 [图片] 第二种方法:直接使用数组下标 云函数代码 [图片] test_api集合原始数据如下 [图片] 代码执行后 [图片] 相对于第一种方法,这种方法更加简单,只不过users.1.test这种写法有点颠覆js和java中的属性书写规则,让人感觉怪怪的,在mongoDB中,也支持点数字这种写法。 一个可能的疑惑 可不可以写作’users[1].test’:‘test’,测试结果如下: [图片] [图片] 可以看到’user[1]'无法被识别为数组的第二个元素,而是作为了属性名新增了一个属性,结论:必须写成”点数字“不能写成“中括号” 结论: 经过测试,使用这两种种方法可以更新数组中的一个元素。 方法一适合在不知道数组元素下标的情况下根据查询条件更新元素; 方法二适合在知道数组元素下标的情况下更新元素; 当然也存在既知道元素下标也可以通过属性查到的情况,想用哪个就看心情了-.- 但是暂未找到查询返回数组中的一个元素的方法,再探索探索吧 ——。——
2019-03-06 - 云函数生成小程序码并上传到云存储
同理可以将网络其他文件上传到云存储 首先安装 request-promise npm 命令 npm install request-promise // 云函数入口文件 const cloud = require('wx-server-sdk') //npm install request-promise const rp = require('request-promise'); cloud.init() // 云函数入口函数 exports.main = async (event, context) => { //appid 和秘钥 const appid = 'wxxxxxxxx', secret = 'xxxxxxxxxxxx'; const AccessToken_options = { method: 'GET', url: 'https://api.weixin.qq.com/cgi-bin/token', qs: { appid, secret, grant_type:'client_credential' }, json: true }; //获取AccessToken const resultValue = await rp(AccessToken_options); const token = resultValue.access_token; //获取小程序码配置 const code_options = { method: 'POST', url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='+token, body: { 'page': "pages/index/index", 'width': 430, 'scene': "1111" }, json: true , encoding: null }; //获取二进制图片 const buffer = await rp(code_options); //数据大于10K 上传到云 if (buffer.length>1024*10) { const upload = await cloud.uploadFile({ cloudPath: 'demo5561.jpg', fileContent: buffer, }) return { upload} } return { reslut:buffer} }
2018-11-01