最有效的方法来增加Firebase中所有内容的值

时间:2015-12-24 23:55:04

标签: angularjs firebase firebase-realtime-database

说我的条目看起来像这样:

Firebase Image

我希望将估算列表中的每个项目的priority字段增加1。

我可以抓住这样的估计:

var estimates = firebase.child('Estimates');

之后如何自动将每个Estimates优先级递增1?

2 个答案:

答案 0 :(得分:5)

仅用于FIRESTORE API,不用于FIREBASE

由于使用了最新的Firestore补丁程序(2019年3月13日),您无需遵循上面的其他答案。

Firestore的FieldValue类现在托管一个 increment 方法,该方法可以自动更新Firestore数据库中的数字文档字段。您可以将此FieldValue标记与set对象的update(具有mergeOptions true)或DocumentReference方法一起使用。

用法如下(从官方文档开始,这就是全部):

DocumentReference washingtonRef = db.collection("cities").document("DC");

// Atomically increment the population of the city by 50.
washingtonRef.update("population", FieldValue.increment(50));

如果您想知道,可以从Firestore的18.2.0版本获得。为了您的方便,Gradle依赖项配置为implementation 'com.google.firebase:firebase-firestore:18.2.0'

  

注意:递增操作对于实现计数器很有用,但是   请记住,每个文档只能更新一次   第二。如果您需要将计数器更新到高于此速率,请参阅   Distributed counters页。


编辑1 FieldValue.increment()纯粹是“服务器”端(发生在Firestore中),因此您不需要向客户端公开当前值。

编辑2 :使用管理API时,您可以使用admin.firestore.FieldValue.increment(1)来实现相同的功能。感谢@Jabir Ishaq自愿让我知道未记录的功能。 :)

编辑3 :如果要递增/递减的目标字段不是数字或不存在,则increment方法会将值设置为当前值!首次创建文档时,这很有用。

答案 1 :(得分:3)

这是循环所有项目并提高其优先级的一种方法:

var estimatesRef = firebase.child('Estimates');
estimatesRef.once('value', function(estimatesSnapshot) {
  estimatesSnapshot.forEach(function(estimateSnapshot) {
    estimateSnapshot.ref().update({
      estimateSnapshot.val().priority + 1
    });
  });
});

它遍历Estimates的所有孩子,并提高每个孩子的优先级。

您还可以将通话合并为一个update()通话:

var estimatesRef = firebase.child('Estimates');
estimatesRef.once('value', function(estimatesSnapshot) {
  var updates = {};
  estimatesSnapshot.forEach(function(estimateSnapshot) {
    updates[estimateSnapshot.key+'/priority'] = estimateSnapshot.val().priority + 1;
  });
  estimatesRef.update(updates);
});

性能与第一个解决方案类似(Firebase在处理多个请求时非常高效)。但在第二种情况下,它将向服务器发送一个命令,因此它将失败或完全成功。

相关问题