0

의 크기를 계산하는, 내가 count increase/decrease을 달성하기 위해 노력하고 있어요 :중포 기지 클라우드 기능은 아이들이 <a href="https://firebase.google.com/docs/reference/functions/functions.database.DeltaSnapshot#val" rel="nofollow noreferrer">firebase cloud functions API reference</a> 다음

Uploads/ 
    - Posts/ 
      - post_1 
      - post_2 
      ... 

    - Likes/ 
      - post_1/ 
       - Number: 4 
      - post_2/ 
       - Number: 2 
      ... 

그리고, 위치 이외의

exports.LikeCount= functions.database.ref('/Posts/{postID}').onWrite(event => { 
    const Ref  = event.data.ref; 
    const postID = event.params.postID; 
    const likeCount= Ref.parent.parent.child('/Likes/' + postID + '/Number');   

    return likeCount.transaction(current => {   
     if (event.data.exists() && !event.data.previous.exists()) { 
      return (current || 0) + 1; 

     }else if (!event.data.exists() && event.data.previous.exists()) { 
      return (current || 0) - 1; 

     } 

    }).then(() => { 
     console.log("Done");   
    }); 
}); 

를, 그것은 주어진 예와 동일합니다.

another example 좋아하는 사람의 수가 삭제되면 좋아하는 사람 (아동)의 수를 다시 계산합니다.

여기 내 버전 (또는 적어도 아이디어)은 좋아요 수를 확인하고 1보다 작 으면 다시 계산합니다. (단지 좋아하는 수가 존재하지 않으면 존재하는 수의 수에 관계없이 첫 번째 함수가 1을 줄 것이라는 이유만으로). 두 번째 기능으로

exports.reCount= functions.database.ref('/Likes/{postID}/Number').onUpdate(event => { 
    const value = event.data.val; 

    //If the value is less than 1: 
    if (value <= 1) { 
     const currentRef = event.data.ref; 
     const postID  = event.params.postID;    
     const postRef = currentRef.parent.parent.child('/Uploads/Posts/{postID}/');    

     return postRef.once('value') 
      .then(likeData=> currentRef.set(likeData.numChildren()));    
    } 
}); 

, 내가 사용 Number 값을 얻기 위해 노력 내가 문자열 값을 얻을 것이라고 생각 FB 로그에 [Function: val]을 준 다음과 같은 경우 event.data.val.

... 및 currentRef.parent.parent.child('/Uploads/Posts/{postID}/').numChilren();TypeError: collectionRef.numChildren is not a function입니다.

나는 온라인 튜토리얼과 API 레퍼런스를 읽었지만 여전히 문자열 값을 얻을 수없는 이유에 대해 혼란 스럽다.

나는 내가 할 수있는 몇 가지 예를 찾고있다.

+0

[Firebase를위한 구름 기능 : 증가 카운터] (https://stackoverflow.com/questions/42914815/cloud-functions-for-firebase-increment-counter) –

+0

나는 이것을 읽었습니다. 제가 물어 본 질문은 실제로 링크에서 대답하지 않습니다. –

+0

"예상대로 작동하지 않습니다"이외의 관측이 있습니까? –

답변

5

여기에 여러 가지 문제가 있습니다.

로그에서 알 수 있듯이 event.data.val은 기능입니다. 당신은 변경 위치에서 자바 스크립트 객체를 얻기 위해 val()를 호출해야합니다 : event.data.val()

두 번째 문제 : 이미 위치의 절대 경로를 조회 할 알고있을 때 당신이 currentRef.parent.parent.child를 사용하는 이유는 확실하지 않다. 당신은 직접이 얻을 수 있습니다 : /Uploads/Posts/{postID}/ :

currentRef.root.ref(`/Uploads/Posts/${postID}/`) 

세 번째 것은,이 문자열을 구축 할 변수 보간을 사용하기위한 시도의 모습에 작은 따옴표를 사용하고 있습니다. 이것을 위해 backticks를 사용해야하고, 거기에 $ {}을 사용하여 변수를 삽입해야합니다 ($를 생략하고 있음).

마지막으로, 동일한 위치를 변경하려고 할 때 두 개의 함수가 동시에 실행될 수 있기 때문에 다른 샘플 코드에서 볼 수 있듯이 트랜잭션을 사용하여 쓰기를 수행해야합니다. 나는 그것을 밖으로 남겨 두지 말라고 woudldn't.

+0

덕 감사합니다. 이러한 피드백은 도움이되었습니다. 매우 감사! –

관련 문제