在 Firebase 中增加所有值的最有效方法 [英] Most efficient way to increment a value of everything in Firebase
问题描述
假设我有这样的条目:
我想为估计列表中的每个项目将 priority
字段增加 1.
And I want to increment the priority
field by 1 for every Item in the list of Estimates.
我可以这样获取估算值:
I can grab the estimates like this:
var estimates = firebase.child('Estimates');
在那之后,我如何将每个 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屋!