const { sub_stock_num } = event
const _id = '文档ID'
try {
const wxContext = cloud.getWXContext()
const openid = wxContext.OPENID
const db = cloud.database({
throwOnNotFound: false,
})
const _ = db.command
const transaction = await db.startTransaction()
const user_transaction = transaction.collection('2023user_skus')
const user = await user_transaction.doc(_id).get()
const { stocks } = user.data
const markMutations = (stocks, sub_stock_num) => {
let str = '{'
for (let i = 0; i < sub_stock_num.length; i++) {
let index = stocks.findIndex(e => e.out_sku_id == sub_stock_num[i]['out_sku_id'])
if (index != -1) {
str = str.concat(`"stocks.${index}.stock_num":_.inc(-${sub_stock_num[i]['sub_stock_num']}),`)
}
}
return str.substring(0, str.length - 1) + '}'
}
const fs = markMutations(stocks, sub_stock_num)
console.log(fs);
const updates = await user_transaction.doc(_id).update({
data: eval("(" + fs + ")")
})
await transaction.commit()
return {
success: true,
data: updates
}
} catch (e) {
console.log(e);
return {
success: false,
error: 1,
errmsg: e
}
}
const { _id, sub_stock_num } = event try { //获取微信调用上下文 const wxContext = cloud.getWXContext() const openid = wxContext.OPENID const db = cloud.database({ throwOnNotFound: false, }) const _ = db.command const transaction = await db.startTransaction() const user_transaction = transaction.collection('2023user_skus') // 1. 获取用户信息 const user = await user_transaction.doc(_id).get() // 2. 获取商品库存信息 const { stocks } = user.data const markMutations = (stocks, sub_stock_num) => { let up_obj = {} for (let i = 0; i < sub_stock_num.length; i++) { // 3. 查找当前 out_sku_id 的对应库存 在stocks数组中的下标 let index = stocks.findIndex(e => e.out_sku_id == sub_stock_num[i]['out_sku_id']) if (index != -1) { // 4. 拼接更新的内容 up_obj[`stocks.${index}.stock_num`] = _.inc(-sub_stock_num[i]['sub_stock_num']) } } console.log(up_obj); return up_obj } // 5. 更新数据 const updates = await user_transaction.doc(_id).update({ data: markMutations(stocks, sub_stock_num) }) await transaction.commit() return { success: true, data: updates } } catch (e) { console.log(e); //回滚三次 抛出错误 返回 success: false 和 错误信息 前端判断 res.result.success return { success: false, error: 1, errmsg: e } } //这样也可以