提醒大家:一定要仔細看文檔!
背景
我從小程序端collection.get來判斷數據庫是否有該用戶的記錄,沒有則通過雲函數創建一個。
但是小程序能get到數據庫的內容,雲函數缺一直add不進去,查看日誌發現函數調用成功,但是返回的全是null
。
報錯內容是:
2019-08-22T10:55:41.458Z { 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.;
數據集合不存在
我知道的可能原因有兩個:1.數據庫沒有對應的集合;2.雲函數與數據庫沒在一個環境
第一個直接排除,問題果然出在第二個上面。
我申請過兩個環境,暫且稱爲環境A(id:123)、環境B(id:321),A是先申請的,是默認環境。
我在小程序的app.js
將小程序的雲環境初始化爲環境B。
if (!wx.cloud) {
console.error('請使用 2.2.3 或以上的基礎庫以使用雲能力')
} else {
wx.cloud.init({
// 此處請填入環境 ID, 環境 ID 可打開雲控制檯查看
env: '321',
traceUser: true
})
}
}
但是在雲函數裏用的卻是默認的初始化。
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
exports.main = async(event, context) => {
try {
return await db.collection('busers').add({
data: {
year: event.year,
month: event.month
}
})
}catch(e){
console.error(e)
}
}
這樣的話雲函數操作的是環境A中的數據庫,A中沒有busers集合,所以error了。
初始化時指定爲B環境就ok了。
const cloud = require('wx-server-sdk')
cloud.init({
env: '321',
traceUser: true
})
const db = cloud.database()
exports.main = async(event, context) => {
try {
return await db.collection('busers').add({
data: {
year: event.year,
month: event.month
}
})
}catch(e){
console.error(e)
}
}