云开发的数据库api的add方法返回null,并没有返回id,请问是什么原因呢?
发布于 4 年前 作者 minghou 1199 次浏览 来自 问答

db.collection("test").add()方法

基础库:2.10.1

// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
  return new Promise((resolve,reject)=>{
    db.collection("travelRecord").add({
      data:{
        openId:event.openId,
      },
      success:function(res){
        resolve(res)
      }
    })
  })
}
这种方式没有能拿到返回值

exports.main = async (event, context) => {
  return new Promise((resolve,reject)=>{
    db.collection("travelRecord").add({
      data:{
        openId:event.openId,
      }
    }).then(res=>{
      resolve(res)
   })
    }
同样返回null,但是集合是正常添加上记录的,过一小段时间(云函数创建部署完有个五分钟左右)则会有返回值
1 回复
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
exports.main = async (event, context) => {
  try {
    return await db.collection('todos').add({
      // data 字段表示需新增的 JSON 数据
      data: {
        description: "learn cloud database",
        due: new Date("2018-09-01"),
        tags: [
          "cloud",
          "database"
        ],
        // 位置(113°E,23°N)
        location: new db.Geo.Point(113, 23),
        done: false
      }
    })
  } catch(e) {
    console.error(e)
  }
}

官方的示例代码没问题,我猜是你集合名字的问题,你可以本地调试下看看
回到顶部