简体   繁体   中英

How to stop reading child_added with Firebase cloud functions?

I try to get all 10 records using this:

exports.checkchanges = functions.database.ref('school/{class}').onCreate(snap => {

    const class=snap.params.class;

    var ref = admin.database().ref('/students')
    return ref.orderByChild(class).startAt('-').on("child_added", function(snapshot) {

        const age=snapshot.child("age");
        // do the thing

    })
)}

The problem is that after I get the 10 records I need correctly, even after few days when a new record is added meeting those terms, this function is still invoked.

When I change on("child_added to once("child_added I get only 1 record instead of 10. And when I change on("child_added to on("value I get null on this:

const age=snapshot.child("age");

So how can I prevent the function from being invoked for future changes?

When you implement database interactions in Cloud Functions, it is important to have a deterministic end condition. Otherwise the Cloud Functions environment doesn't know when your code is done, and it may either kill it too soon, or keep it running (and thus billing you) longer than is necessary.

The problem with your code is that you attach a listener with on and then never remove it. In addition (since on() doesn't return a promise), Cloud Functions doesn't know that you're done. The result is that your on() listener may live indefinitely.

That's why in most Cloud Functions that use the Realtime Database, you'll see them using once() . To get all children with a once() , we'll listen for the value event:

exports.checkchanges = functions.database.ref('school/{class}').onCreate(snap => {

    const class=snap.params.class;

    var ref = admin.database().ref('/students')
    return ref.orderByChild(class).startAt('-').limitToFirst(10).once("value", function(snapshot) {
      snapshot.forEach(function(child) {
        const age=child.child("age");
        // do the thing
      });
    })
)}

I added a limitToFirst(10) , since you indicated that you only need 10 children.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM