errCode: -502005 database collection not exists

提醒大家:一定要仔细看文档!


背景

我从小程序端collection.get来判断数据库是否有该用户的记录,没有则通过云函数创建一个。

collection.get
result
callFunction
collection.add
小程序
云数据库
云函数

但是小程序能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)
  }
}

初始化的知识不只这些,建议看看官方文档云能力初始化数据库引用初始化

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章