完整代码大概长这样,是个云函数来的,用的腾讯云:
'use strict';
const db = uniCloud.database();
exports.main = async (data, context) => {
const tx = await db.startTransaction();
try {
// 查询是否已存在记录
const existsRes = await tx.collection('test').where({
action_type: data.action_type,
target_type: data.target_type,
target_id: data.target_id
}).get();
const existsData = _.get(existsRes, 'data[0]');
if (_.isEmpty(existsData)) {
// 不存在则新增
await tx.collection('test').add(data);
} else {
// 存在即删除
await tx.collection('test').doc(existsData._id).remove();
}
await tx.commit();
// 查询计数
const countRes = await db.collection('test').
where({
target_type: data.target_type,
target_id: data.target_id,
action_type: data.action_type
}).
count()
const countData = _.get(countRes, 'total')
const updateDoc = { tt_count: countData };
const updateRes = await db.collection('test').
doc(data.target_id).
update(updateDoc);
if (updateRes.updated <= 0) {
throw new Error(`更新总数失败`);
}
return { code: 0, data: 'ok' }
} catch (e) {
await tx.rollback(-100);
return { code: -1, msg: 'error' }
}
};
鱼忆科技 (作者)
见下面回复
2021-06-25 11:15