小程序云开发查询数据库返回的值是什么样子的?
发布于 6 年前 作者 yongjia 14223 次浏览 最后一次编辑是 5 年前 来自 官方Issues

我想要在云函数里面做一些逻辑判断,但是始终获取不到Collection.get()中的值

想要在添加一条数据之前先判断数据库中是否存在,不存在则新增

但是在if那个位置一直不知道怎么去判断

cool是中间变量

我尝试着把cool stringify,但是出来的东西是空的 但是return到小程序那边又有值在里面

const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  var cool = null
  try {
    console.log('openid:' + event._openid)
    cool = db.collection('user_info').where({
      _openid:event._openid
    }).get({
      success: function (res) {
        return res
      }
    });
  } catch (e) {
    console.error(e);
  }
  
  if (cool.data._openid==undefined){
    db.collection('user_info').add({
      // data 字段表示需新增的 JSON 数据
      data: {
        _openid: wxContext.OPENID,
      }
    })
    console.log("没有找到openid,新增成功")
    cool = db.collection('user_info').where({
      _openid: event._openid
    }).get({
      success: function (res) {
        return res
      }
    });
  }
  console.log("cool2str:" + JSON.stringify(cool));
  return cool
}
5 回复

是异步的问题吧,改成同步的。

云函数里凡是看不到await,只有success的,都会有问题。

你这写法也太混乱了…

collection.get() 的返回值是在 success 的回调函数中的:

    db.collection('user_info').where({
      _openid:event._openid
    }).get({
      success: function (res) {
        // res 中包含 get() 获取的数据
        return res
      }
    });
cool = await db.collection('user_info').where({
      _openid:event._openid
    }).get();
这样子写cool就能获取到了,数据库操作是异步的,
还有要判断一个值是否存在,可以在where查询的时候,使用下面这个查询条件
https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/database/command/Command.exists.html
回到顶部