2017-08-16 28 views
0

我正在構建一個步驟計數器應用程序。 我得到了一個iOS應用是推動每一天/用戶/ {移動} /措施/ {日期}/ 當一個新的步驟,孩子被更新或添加的總和,我要總結的針對所有步驟的價值特定用戶並更新他的stepsTotal如何增加Firebase中現有對象的值?

爲了實現這個目標,我需要

  1. 找到原來的用戶和總結的所有步驟。
  2. 保存新的價值stepsTotal。

我將不勝感激,如果有人在這裏可以給予一定的幫助。 :-)

數據庫

{ 

    "users": { 
    "92291000": { 
     "firstName": "Tore", 
     "stepsTotal": "1500", 
     "steps": { 
     "02-09-2017": "500", 
     "03-09-2017": "1000" 
     }, 

import.js

var db  = admin.database(); 
var dbRoot = db.ref("/"); 
var usersRef = dbRoot.child("users"); 

// This works  
function saveUser(attributes) { 
    let mobile = attributes.mobile; 
    delete attributes['mobile'] 
    let user = usersRef.child(mobile); 
    user.update(attributes); 
} 


function increaseSteps({ mobile=null, steps=null } = {}) { 
    // Find the User 
    console.log("looking for mobile", mobile); // OK 
    let userRef = usersRef.child(mobile); 

    // Here I'm not able to read the old data from the user. 
    userRef.transaction(function(user) { 
    console.log("user: ", user); // null 
    //^User is null. 
    }); 


/* 
    If I mangage to find user above, I expect to do something like this. 
    Or it is possible to only update *stepsTotal*? 
*/ 

    let attributes = { 
    firstName: user.firstName, 
    lastName: user.lastName, 
    stepsTotal: user.stepsTotal + steps, 
    } 
    user.update(attributes); 
} 

回答

0

如果我理解正確的話,你必須在這個片段中的代碼的問題:

let userRef = usersRef.child(mobile); 

// Here I'm not able to read the old data from the user. 
userRef.transaction(function(user) { 
    console.log("user: ", user); // null 
    //^User is null. 
}); 

在火力地堡數據庫交易的初始值通常是null。從Firebase documentation on transactions

交易功能被多次調用

您的交易處理程序被調用多次,並且必須能夠處理null數據。即使數據庫中存在數據,當事務函數運行時,它也可能不會被本地緩存。

這是由於火力地堡事務如何在幕後工作。要了解更多有關的是,在這裏看到Transcation updateFunction parameter is nullFirebase runTransaction not working我的答案。

的解決方案是處理這兩種情況:如果用戶節點不存在尚未計數的步驟的初始數量,否則更新的步驟的數目:

let userRef = usersRef.child(mobile); 

userRef.transaction(function(user) { 
    return (user || 0) + new_steps_for_user; 
}); 
相關問題