问题描述:
小程序云开发切换运行环境时,进行了以下修改:
最关键一步是:
app.js里的初始化,要给env设置参数,否则用的是默认环境,就是第一个创建的环境。
这里的环境ID不是你自己设置的那个环境名,要去控制台的设置里查看
重点来了
设置完之后本以为万事大吉,我还是太天真了
调用云函数返回异常:
reason: Error: errCode: -502005 database collection not exists | errMsg: [ResourceNotFound] Db or Table not exist. Please check your request, but if the problem cannot be solved, contact us.;
调用的是 x-test 的环境不假,但是云函数里却找不到当前环境的数据库集合。
查阅微信官方文档:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/init/server.init.html
原来需要在云函数里指定相关环境:
const db = cloud.database({
env:'x-test-n76tb'
});
可是问题又来了,从不能每次发布要把所有云函数都改一遍吧,那也太不友好了。
再查文档:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/constant/constant.html#示例
获取数据库时设置参数:env
const db = cloud.database({ env: cloud.DYNAMIC_CURRENT_ENV })
这样设置,自动获取当前环境数据库,真香!