const cloud = require('wx-server-sdk')
cloud.init({
env: 'cloud1-7gfkdvn4d13b54c9'
})
const db = cloud.database({});
exports.main = async (event) => {
try {
const result = await db.runTransaction(async transaction => {
const userRes = await transaction.collection('user').doc(event.user_id).get()
if (userRes.data) {
const updateuserRes = await transaction.collection('user').doc(event.user_id).update({
data: {
balance: userRes.data[0].balance - event.cost,
}
})
const updatehistoryRes = await transaction.collection('history').add({
data: {
name:event.name,
stamp:event.stamp,
num:event.cost,
type:0, //0表示钱包减少,1表示钱包增加
}
})
return {
balance: userRes.data[0].balance-event.cost,
}
} else {
await transaction.rollback('失败了')
}
})
return {
success: true,
result:result,
}
} catch (e) {
console.error(`事务报错`, e)
return {
success: false,
error: e
}
}
}
解决了,应该改写成userRes.data.balance-event.cost