In Firebase, how can I query the most recent 10 child nodes?

前端 未结 3 908
醉话见心
醉话见心 2020-11-28 14:47

I\'m using childByAutoId() to generate my children. Each child looks like:

{
    user_id: 1
}

I\'d like to get the last 10 mos

3条回答
  •  醉话见心
    2020-11-28 15:32

    I'm assuming your data actually looks like this:

    someDataSet: {
        longUID-1: {
            timeCreated: 9999999999, // (seconds since the javascript epoch)
            user_id: 1
        },
        longUID-2: {
            timeCreated: 1111111111,
            user_id: 2
        },
        longUID-3: {
            timeCreated: 3141592653,
            user_id: 3
        }
    }
    

    You could automate that by calling Firebase.push({user_id: ###, timeCreated: ###}) multiple times in a for loop or any other method. Maybe you're adding news stories to a webpage, but you only want your user to see the most current stories--- IDK. But the answer to your question is to use Firebase's ref.orderByChild() and ref.limitToLast().

    var ref = new Firebase(".firebaseio.com/someDataSet"); 
        //the "/someDataSet" comes from the arbitrary name that I used up above
    
    var sortedRef = ref.orderByChild('timeCreated');
        //sort them by timeCreated, ascending
    
    sortedRef.limitToLast(2).on("child_added", function(snapshot){
        var data = snapshot.val();
    
        console.log(data);
    
        /* do something else with the data */
    });
    
    //The console would look like this
    
    // Object {timeCreated: 9999999999, user_id: 1}
    // Object {timeCreated: 3141592653, user_id: 3}
    

    This happened because the program took the child with the greatest timeCreated value first and then the second greatest (value) second... Also note, the longUID means nothing when you sort them by child and neither do the other values (user_id in this case)

    Here is the documentation for:

    • Firebase .push() method (Sorry, I'm not allowed to post this link- I dont have enough reputation)
    • Firebase .orderByChild method
    • And also, Firebase .limitToLast method

提交回复
热议问题