收藏
回答

事务内能判断后执行吗?

框架类型 问题类型 终端类型 AppID 环境ID 基础库版本
小程序 Bug 微信安卓客户端 wx938181215591f46f community-0glnlwlc358c3494 2.14.1

场景:一个用户进入小程序后,需要判断是否新用户(判断test_user表内是否包含此用户的openid),没有存在则新增,

因为业务需要,小程序可能会多次发起这个判断请求,所以考虑用事务

index.js页面测试代码(多次请求):

Page({
  data: {},
  onLoad() {
    this.isNew()
    this.isNew()
    this.isNew()
    this.isNew()
    this.isNew()
    this.isNew()
    this.isNew()
    this.isNew()
    this.isNew()
    this.isNew()
    this.isNew()
    this.isNew()
    this.isNew()
    this.isNew()
    this.isNew()
    this.isNew()
  },
  onShow() { this.isNew() },
  isNew() {
    wx.cloud.callFunction({
      name: 'testOpenid',
      data: {
        table1: 'test_user'
      }
    }).then(res => {
      console.log(res);
    })
  },
})

云函数代码

// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
//初始化数据库
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
  console.log(event);
  const wxContext = cloud.getWXContext()
  let openid = wxContext.OPENID
  let unionid = wxContext.UNIONID
  try {
    const result = await db.runTransaction(async transaction => {
      const aaaRes = await transaction.collection(event.table1).where({ _openid: openid }).get();
      console.log(19, aaaRes);
      if (aaaRes.data) {
        const updateAAARes = await transaction.collection(event.table1).where({ _openid: openid }).get().then(res => {
          console.log(res);
          for (let i = 0; i < res.data.length; i++) {
            const item = res.data[i];
            if (item._openid === openid) {
              console.log('不是新用户');
              return {
                aaaAccount: aaaRes.data._id,
              }
            }
          }
          console.log('这里执行新增');
          transaction.collection(event.table1)
            .add({
              data: {
                _openid: openid,
                unionid: unionid,
              }
            })
        })
        console.log(`transaction succeeded`)
        // 会作为 runTransaction resolve 的结果返回
        return {
          aaaAccount: aaaRes.data._id,
        }
      } else {
        // 会作为 runTransaction reject 的结果出去
        await transaction.rollback(-100)
        console.log('回滚')
      }
    })
    return {
      success: true,
      aaaAccount: result.aaaAccount,
    }
  } catch (e) {
    console.error(`transaction error`, e)
    return {
      success: false,
      error: e
    }
  }
}


实际事务没有起作用,同时更新了多条数据,正常应该只有一条数据

事务日志报错(偶尔出现几条):

问题:

1.官方写了不能用where,实际用了能跑起来,不知道是不是这个原因报错

2.我这个需求不用where不行,因为需要查询openid判断当前用户是否新用户

3.试过where和doc都不用,也能跑,但也报上面那俩个错,而且事务也不起作用

4.若这种情况不能放到事务,各位大佬有什么建议吗

回答关注问题邀请回答
收藏

1 个回答

  • ZiraLi
    ZiraLi
    2021-09-10

    直接用_id,就可以了把用户openid直接=文档id

    2021-09-10
    有用
    回复
登录 后发表内容
问题标签