node.js - Firebase 事务一次更新文档中的多个字段
问题描述
我正在尝试读取 firestore 文档中的单个字段,将该字段加一并沿文档中的其他两个字段更新该字段。
似乎 firebase 事务更新()函数接受只有一个字段和值的 JSON 对象,因为当我将其他字段添加到 JSON 时,更新失败。
这有效:
t.update(referralCodesDocRef, {field1: value1});
这不起作用:
t.update(referralCodesDocRef, {
field1: value1,
field2: value2,
field3: value3
});
这也不起作用:
t.update(referralCodesDocRef, {field1: value1});
t.update(referralCodesDocRef, {field2: value2});
t.update(referralCodesDocRef, {field3: value3});
这是进行交易的功能
function runIncreaseCountTransaction(referralCodesDocRef){
return db.runTransaction(t => {
return t.get(referralCodesDocRef)
.then(doc => {
console.log(doc);
let newReferralCount = doc.data().referral_count + 1;
if(newReferralCount === max_referral_count){
const current_time_millis = Date.now();
const end_time_millis = current_time_millis+(180*1000); // ends after 3 mins
t.update(referralCodesDocRef, {referral_count: newReferralCount});
t.update(referralCodesDocRef, { timer_start_time: current_time_millis });
t.update(referralCodesDocRef, { timer_end_time: end_time_millis });
}
else{
t.update(referralCodesDocRef, { referral_count: newReferralCount });
}
return Promise.resolve(newReferralCount);
})
.then(result => {
console.log('Success: Update successful: Referral count incremented!!', result);
return true;
}).catch(err => {
console.log('Error: could not update referral count', err);
});
});
}
那么如何通过firebase事务实现多个字段更新呢?
解决方案
使用由多个属性组成的 JavaScript 对象更新文档应该完全没有问题,例如
t.update(referralCodesDocRef, {
field1: value1,
field2: value2,
field3: value3
});
问题很可能来自这样一个事实,即您没有返回事务update()
方法返回的事务。以下应该可以解决问题:
function runIncreaseCountTransaction(referralCodesDocRef){
return db.runTransaction(t => {
return t.get(referralCodesDocRef)
.then(doc => {
console.log(doc);
let newReferralCount = doc.data().referral_count + 1;
if (newReferralCount === max_referral_count) {
const current_time_millis = Date.now();
const end_time_millis = current_time_millis+(180*1000); // ends after 3 mins
return t.update(referralCodesDocRef,
{
referral_count: newReferralCount,
timer_start_time: current_time_millis,
timer_end_time: end_time_millis
});
} else{
return t.update(referralCodesDocRef, { referral_count: newReferralCount });
}
});
})
.then(result => {
console.log('Success: Update successful: Referral count incremented!!', result);
return null;
})
.catch(err => {
console.log('Error: could not update referral count', err);
return null; //Note the return here.
});
}
推荐阅读
- mysql - 无法使用 SQL 实现数组到字符串
- linux - Grep 获取文本文件中的特定数字并输出每个数字文本文件
- python - 使用 Pillow 在图像上传 Django 2 上调整大小和创建缩略图
- ionic-framework - ionic svg-icons - 改变背景颜色
- localhost - (本地主机)SQL Server 2014 未与称重秤通信
- javascript - React.js 异步渲染:何时多次调用 componentWillMount
- java - 我的拖放在 Android Studio 中不起作用
- react-native - Flatlist 状态更新中的动态文本输入
- mysql - 这个问题是什么错误,请解释一下
- powershell-6.0 - 导出 Csv 和数组对象