在Firebase中增加所有值的最有效方法 [英] Most efficient way to increment a value of everything in Firebase

查看:87
本文介绍了在Firebase中增加所有值的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Say I have entries that look like this:

我想将估计"列表中的每个项目的priority字段加1.

And I want to increment the priority field by 1 for every Item in the list of Estimates.

我可以这样估算:

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

之后,我如何将每个估算"优先级自动递增1?

After that how would I auto increment every Estimates priority by 1?

推荐答案

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

This is one way to loop over all items and increase their priority:

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

它循环遍历Estimates的所有子级,并增加每个子级的优先级.

It loops over all children of Estimates and increases the priority of each.

您还可以将这些呼叫合并为单个update()呼叫:

You can also combine the calls into a single update() call:

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在处理多个请求时非常高效).但是在第二种情况下,它将向服务器发送单个命令,因此它将失败或完全成功.

The performance will be similar to the first solution (Firebase is very efficient when it comes to handling multiple requests). But in the second case it will be sent a single command to the server, so it will either fail or succeed completely.

这篇关于在Firebase中增加所有值的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆