Firebase & Filtering ordering by value/key











up vote
1
down vote

favorite












I have the following structure in Firebase:



enter image description here



I would like to retrieve only the dates falling within a given range, and for that I was using the following return getMealsRefForUser().orderByValue().equalTo("2018-11-17");, where the reference is mealsRefForUser= firebaseDatabase.getReference(MEALS_OF).child(user.getUid());.
However, the filtering does not happen. What am I missing?



EDIT: So, I am always getting the /mealsOf/<userId> node, even if I qualify it by orderByKey().startAt().endAt(), although my aim is to get a data snapshot that contains a bunch of nodes whose <year>-<month>-<day> "tag" is within the given range.



EDIT: What I am trying to achieve is to bind LiveData to a query like this:



public FirebaseQueryLiveData( Constraints c ) {
if ( c == null )
this.query= FirebaseDatabase.getInstance()
.getReference("/mealsOf")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
else
this.query= FirebaseDatabase.getInstance()
.getReference("/mealsOf")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.orderByKey().startAt(c.dayFrom).endAt(c.dayTo);
}


But this ends up giving me the entire list, all the same -- regardless of the constraints.
The whole source code of the class:



// https://firebase.googleblog.com/2017/12/using-android-architecture-components.html
public class FirebaseQueryLiveData extends LiveData<DataSnapshot> {

private static final String TAG = "FirebaseQueryLiveData";
private boolean listenerRemovePending= false;
private final Handler handler= new Handler();

private final Runnable removeListener= new Runnable() {
@Override
public void run() {
query.removeEventListener(listener);
listenerRemovePending= false;
}
};

private static final String LOG_TAG= "FirebaseQueryLiveData";

private final Query query;
private final InnerValueEventListener listener= new InnerValueEventListener();

public FirebaseQueryLiveData( Constraints c ) {
if ( c == null )
this.query= FirebaseDatabase.getInstance()
.getReference("/mealsOf")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
else
this.query= FirebaseDatabase.getInstance()
.getReference("/mealsOf")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.orderByKey().startAt(c.dayFrom).endAt(c.dayTo);
}

public FirebaseQueryLiveData( DatabaseReference ref ) {
this.query= ref;
}

@Override
protected void onActive() {
//Log.d(LOG_TAG, "onActive");
if ( listenerRemovePending )
handler.removeCallbacks(removeListener);
else
query.addValueEventListener(listener);
listenerRemovePending= false ;
}

@Override
protected void onInactive() {
//Log.d(LOG_TAG, "onInactive");
handler.postDelayed(removeListener,2000);
listenerRemovePending= true ;
//query.removeEventListener(listener);
}

private class InnerValueEventListener implements ValueEventListener {
@Override
public void onDataChange( @NonNull DataSnapshot dataSnapshot ) {
setValue(dataSnapshot);
}
@Override
public void onCancelled( @NonNull DatabaseError databaseError ) {
Log.e(LOG_TAG, "Can not listen to query " + query,databaseError.toException());
}
}
}


I think I know what is happening. I have this piece in my code:
viewModel= ViewModelProviders.of(this, new CustomViewModelFactory(c))
.get(MealListViewModel.class);



It is not firing when I supply new query constraints. Does it mean that I can get only one viewmodelprovider per run of my application?



EDIT: In the above updated image, under the meals child of a date I have the division by hours -- e.g. 20 being 8PM etc. How would I restrict my query from both axes -- days and hours?
Before I hear (I must admit appropriate) comments that I need to restructure my database schema, I would like to know if that is possible.
Would we need something along the lines of the following?



 return await dbroot.ref(`mealsOf/${userId}`)
.orderByKey().startAt(dayFrom).endAt(dayTo)
.orderByChild("meals")
.startAt(`${hourFrom}:00`).endAt(`${hourTo}:59`)


Or alternatively, should I keep another location such as duplicate/{userId}/{day}/{hour} to enable queries such as



return await dbroot.ref(`duplicate/${userId}`)
.orderByKey().startAt(dayFrom).endAt(dayTo)
.orderByKey()
.startAt(`${hourFrom}:00`).endAt(`${hourTo}:59`)









share|improve this question
























  • ("2018-11-17") is not a value except a name. I suggest changing your database structure.
    – Kristofer
    Nov 18 at 22:57










  • check the database rules if it's not returning any data it has happened with me a lot that i forgot to edit database rules or when i create new node i forget to define the rules and if it is ruteurning you data then just show a bit more code so that it can be understood whats wrong
    – Har Kal
    Nov 18 at 23:02






  • 1




    the dates are keys here. why are you ordering by value? it should be orderByKey
    – Reza Nasiri
    Nov 18 at 23:23










  • @RezaNasiri: I did try orderByKey, same result -- I get the whole bunch instead of the filtered list.
    – Ilonpilaaja
    Nov 19 at 0:51















up vote
1
down vote

favorite












I have the following structure in Firebase:



enter image description here



I would like to retrieve only the dates falling within a given range, and for that I was using the following return getMealsRefForUser().orderByValue().equalTo("2018-11-17");, where the reference is mealsRefForUser= firebaseDatabase.getReference(MEALS_OF).child(user.getUid());.
However, the filtering does not happen. What am I missing?



EDIT: So, I am always getting the /mealsOf/<userId> node, even if I qualify it by orderByKey().startAt().endAt(), although my aim is to get a data snapshot that contains a bunch of nodes whose <year>-<month>-<day> "tag" is within the given range.



EDIT: What I am trying to achieve is to bind LiveData to a query like this:



public FirebaseQueryLiveData( Constraints c ) {
if ( c == null )
this.query= FirebaseDatabase.getInstance()
.getReference("/mealsOf")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
else
this.query= FirebaseDatabase.getInstance()
.getReference("/mealsOf")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.orderByKey().startAt(c.dayFrom).endAt(c.dayTo);
}


But this ends up giving me the entire list, all the same -- regardless of the constraints.
The whole source code of the class:



// https://firebase.googleblog.com/2017/12/using-android-architecture-components.html
public class FirebaseQueryLiveData extends LiveData<DataSnapshot> {

private static final String TAG = "FirebaseQueryLiveData";
private boolean listenerRemovePending= false;
private final Handler handler= new Handler();

private final Runnable removeListener= new Runnable() {
@Override
public void run() {
query.removeEventListener(listener);
listenerRemovePending= false;
}
};

private static final String LOG_TAG= "FirebaseQueryLiveData";

private final Query query;
private final InnerValueEventListener listener= new InnerValueEventListener();

public FirebaseQueryLiveData( Constraints c ) {
if ( c == null )
this.query= FirebaseDatabase.getInstance()
.getReference("/mealsOf")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
else
this.query= FirebaseDatabase.getInstance()
.getReference("/mealsOf")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.orderByKey().startAt(c.dayFrom).endAt(c.dayTo);
}

public FirebaseQueryLiveData( DatabaseReference ref ) {
this.query= ref;
}

@Override
protected void onActive() {
//Log.d(LOG_TAG, "onActive");
if ( listenerRemovePending )
handler.removeCallbacks(removeListener);
else
query.addValueEventListener(listener);
listenerRemovePending= false ;
}

@Override
protected void onInactive() {
//Log.d(LOG_TAG, "onInactive");
handler.postDelayed(removeListener,2000);
listenerRemovePending= true ;
//query.removeEventListener(listener);
}

private class InnerValueEventListener implements ValueEventListener {
@Override
public void onDataChange( @NonNull DataSnapshot dataSnapshot ) {
setValue(dataSnapshot);
}
@Override
public void onCancelled( @NonNull DatabaseError databaseError ) {
Log.e(LOG_TAG, "Can not listen to query " + query,databaseError.toException());
}
}
}


I think I know what is happening. I have this piece in my code:
viewModel= ViewModelProviders.of(this, new CustomViewModelFactory(c))
.get(MealListViewModel.class);



It is not firing when I supply new query constraints. Does it mean that I can get only one viewmodelprovider per run of my application?



EDIT: In the above updated image, under the meals child of a date I have the division by hours -- e.g. 20 being 8PM etc. How would I restrict my query from both axes -- days and hours?
Before I hear (I must admit appropriate) comments that I need to restructure my database schema, I would like to know if that is possible.
Would we need something along the lines of the following?



 return await dbroot.ref(`mealsOf/${userId}`)
.orderByKey().startAt(dayFrom).endAt(dayTo)
.orderByChild("meals")
.startAt(`${hourFrom}:00`).endAt(`${hourTo}:59`)


Or alternatively, should I keep another location such as duplicate/{userId}/{day}/{hour} to enable queries such as



return await dbroot.ref(`duplicate/${userId}`)
.orderByKey().startAt(dayFrom).endAt(dayTo)
.orderByKey()
.startAt(`${hourFrom}:00`).endAt(`${hourTo}:59`)









share|improve this question
























  • ("2018-11-17") is not a value except a name. I suggest changing your database structure.
    – Kristofer
    Nov 18 at 22:57










  • check the database rules if it's not returning any data it has happened with me a lot that i forgot to edit database rules or when i create new node i forget to define the rules and if it is ruteurning you data then just show a bit more code so that it can be understood whats wrong
    – Har Kal
    Nov 18 at 23:02






  • 1




    the dates are keys here. why are you ordering by value? it should be orderByKey
    – Reza Nasiri
    Nov 18 at 23:23










  • @RezaNasiri: I did try orderByKey, same result -- I get the whole bunch instead of the filtered list.
    – Ilonpilaaja
    Nov 19 at 0:51













up vote
1
down vote

favorite









up vote
1
down vote

favorite











I have the following structure in Firebase:



enter image description here



I would like to retrieve only the dates falling within a given range, and for that I was using the following return getMealsRefForUser().orderByValue().equalTo("2018-11-17");, where the reference is mealsRefForUser= firebaseDatabase.getReference(MEALS_OF).child(user.getUid());.
However, the filtering does not happen. What am I missing?



EDIT: So, I am always getting the /mealsOf/<userId> node, even if I qualify it by orderByKey().startAt().endAt(), although my aim is to get a data snapshot that contains a bunch of nodes whose <year>-<month>-<day> "tag" is within the given range.



EDIT: What I am trying to achieve is to bind LiveData to a query like this:



public FirebaseQueryLiveData( Constraints c ) {
if ( c == null )
this.query= FirebaseDatabase.getInstance()
.getReference("/mealsOf")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
else
this.query= FirebaseDatabase.getInstance()
.getReference("/mealsOf")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.orderByKey().startAt(c.dayFrom).endAt(c.dayTo);
}


But this ends up giving me the entire list, all the same -- regardless of the constraints.
The whole source code of the class:



// https://firebase.googleblog.com/2017/12/using-android-architecture-components.html
public class FirebaseQueryLiveData extends LiveData<DataSnapshot> {

private static final String TAG = "FirebaseQueryLiveData";
private boolean listenerRemovePending= false;
private final Handler handler= new Handler();

private final Runnable removeListener= new Runnable() {
@Override
public void run() {
query.removeEventListener(listener);
listenerRemovePending= false;
}
};

private static final String LOG_TAG= "FirebaseQueryLiveData";

private final Query query;
private final InnerValueEventListener listener= new InnerValueEventListener();

public FirebaseQueryLiveData( Constraints c ) {
if ( c == null )
this.query= FirebaseDatabase.getInstance()
.getReference("/mealsOf")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
else
this.query= FirebaseDatabase.getInstance()
.getReference("/mealsOf")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.orderByKey().startAt(c.dayFrom).endAt(c.dayTo);
}

public FirebaseQueryLiveData( DatabaseReference ref ) {
this.query= ref;
}

@Override
protected void onActive() {
//Log.d(LOG_TAG, "onActive");
if ( listenerRemovePending )
handler.removeCallbacks(removeListener);
else
query.addValueEventListener(listener);
listenerRemovePending= false ;
}

@Override
protected void onInactive() {
//Log.d(LOG_TAG, "onInactive");
handler.postDelayed(removeListener,2000);
listenerRemovePending= true ;
//query.removeEventListener(listener);
}

private class InnerValueEventListener implements ValueEventListener {
@Override
public void onDataChange( @NonNull DataSnapshot dataSnapshot ) {
setValue(dataSnapshot);
}
@Override
public void onCancelled( @NonNull DatabaseError databaseError ) {
Log.e(LOG_TAG, "Can not listen to query " + query,databaseError.toException());
}
}
}


I think I know what is happening. I have this piece in my code:
viewModel= ViewModelProviders.of(this, new CustomViewModelFactory(c))
.get(MealListViewModel.class);



It is not firing when I supply new query constraints. Does it mean that I can get only one viewmodelprovider per run of my application?



EDIT: In the above updated image, under the meals child of a date I have the division by hours -- e.g. 20 being 8PM etc. How would I restrict my query from both axes -- days and hours?
Before I hear (I must admit appropriate) comments that I need to restructure my database schema, I would like to know if that is possible.
Would we need something along the lines of the following?



 return await dbroot.ref(`mealsOf/${userId}`)
.orderByKey().startAt(dayFrom).endAt(dayTo)
.orderByChild("meals")
.startAt(`${hourFrom}:00`).endAt(`${hourTo}:59`)


Or alternatively, should I keep another location such as duplicate/{userId}/{day}/{hour} to enable queries such as



return await dbroot.ref(`duplicate/${userId}`)
.orderByKey().startAt(dayFrom).endAt(dayTo)
.orderByKey()
.startAt(`${hourFrom}:00`).endAt(`${hourTo}:59`)









share|improve this question















I have the following structure in Firebase:



enter image description here



I would like to retrieve only the dates falling within a given range, and for that I was using the following return getMealsRefForUser().orderByValue().equalTo("2018-11-17");, where the reference is mealsRefForUser= firebaseDatabase.getReference(MEALS_OF).child(user.getUid());.
However, the filtering does not happen. What am I missing?



EDIT: So, I am always getting the /mealsOf/<userId> node, even if I qualify it by orderByKey().startAt().endAt(), although my aim is to get a data snapshot that contains a bunch of nodes whose <year>-<month>-<day> "tag" is within the given range.



EDIT: What I am trying to achieve is to bind LiveData to a query like this:



public FirebaseQueryLiveData( Constraints c ) {
if ( c == null )
this.query= FirebaseDatabase.getInstance()
.getReference("/mealsOf")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
else
this.query= FirebaseDatabase.getInstance()
.getReference("/mealsOf")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.orderByKey().startAt(c.dayFrom).endAt(c.dayTo);
}


But this ends up giving me the entire list, all the same -- regardless of the constraints.
The whole source code of the class:



// https://firebase.googleblog.com/2017/12/using-android-architecture-components.html
public class FirebaseQueryLiveData extends LiveData<DataSnapshot> {

private static final String TAG = "FirebaseQueryLiveData";
private boolean listenerRemovePending= false;
private final Handler handler= new Handler();

private final Runnable removeListener= new Runnable() {
@Override
public void run() {
query.removeEventListener(listener);
listenerRemovePending= false;
}
};

private static final String LOG_TAG= "FirebaseQueryLiveData";

private final Query query;
private final InnerValueEventListener listener= new InnerValueEventListener();

public FirebaseQueryLiveData( Constraints c ) {
if ( c == null )
this.query= FirebaseDatabase.getInstance()
.getReference("/mealsOf")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
else
this.query= FirebaseDatabase.getInstance()
.getReference("/mealsOf")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.orderByKey().startAt(c.dayFrom).endAt(c.dayTo);
}

public FirebaseQueryLiveData( DatabaseReference ref ) {
this.query= ref;
}

@Override
protected void onActive() {
//Log.d(LOG_TAG, "onActive");
if ( listenerRemovePending )
handler.removeCallbacks(removeListener);
else
query.addValueEventListener(listener);
listenerRemovePending= false ;
}

@Override
protected void onInactive() {
//Log.d(LOG_TAG, "onInactive");
handler.postDelayed(removeListener,2000);
listenerRemovePending= true ;
//query.removeEventListener(listener);
}

private class InnerValueEventListener implements ValueEventListener {
@Override
public void onDataChange( @NonNull DataSnapshot dataSnapshot ) {
setValue(dataSnapshot);
}
@Override
public void onCancelled( @NonNull DatabaseError databaseError ) {
Log.e(LOG_TAG, "Can not listen to query " + query,databaseError.toException());
}
}
}


I think I know what is happening. I have this piece in my code:
viewModel= ViewModelProviders.of(this, new CustomViewModelFactory(c))
.get(MealListViewModel.class);



It is not firing when I supply new query constraints. Does it mean that I can get only one viewmodelprovider per run of my application?



EDIT: In the above updated image, under the meals child of a date I have the division by hours -- e.g. 20 being 8PM etc. How would I restrict my query from both axes -- days and hours?
Before I hear (I must admit appropriate) comments that I need to restructure my database schema, I would like to know if that is possible.
Would we need something along the lines of the following?



 return await dbroot.ref(`mealsOf/${userId}`)
.orderByKey().startAt(dayFrom).endAt(dayTo)
.orderByChild("meals")
.startAt(`${hourFrom}:00`).endAt(`${hourTo}:59`)


Or alternatively, should I keep another location such as duplicate/{userId}/{day}/{hour} to enable queries such as



return await dbroot.ref(`duplicate/${userId}`)
.orderByKey().startAt(dayFrom).endAt(dayTo)
.orderByKey()
.startAt(`${hourFrom}:00`).endAt(`${hourTo}:59`)






android firebase firebase-realtime-database






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 19 at 8:45

























asked Nov 18 at 22:50









Ilonpilaaja

322214




322214












  • ("2018-11-17") is not a value except a name. I suggest changing your database structure.
    – Kristofer
    Nov 18 at 22:57










  • check the database rules if it's not returning any data it has happened with me a lot that i forgot to edit database rules or when i create new node i forget to define the rules and if it is ruteurning you data then just show a bit more code so that it can be understood whats wrong
    – Har Kal
    Nov 18 at 23:02






  • 1




    the dates are keys here. why are you ordering by value? it should be orderByKey
    – Reza Nasiri
    Nov 18 at 23:23










  • @RezaNasiri: I did try orderByKey, same result -- I get the whole bunch instead of the filtered list.
    – Ilonpilaaja
    Nov 19 at 0:51


















  • ("2018-11-17") is not a value except a name. I suggest changing your database structure.
    – Kristofer
    Nov 18 at 22:57










  • check the database rules if it's not returning any data it has happened with me a lot that i forgot to edit database rules or when i create new node i forget to define the rules and if it is ruteurning you data then just show a bit more code so that it can be understood whats wrong
    – Har Kal
    Nov 18 at 23:02






  • 1




    the dates are keys here. why are you ordering by value? it should be orderByKey
    – Reza Nasiri
    Nov 18 at 23:23










  • @RezaNasiri: I did try orderByKey, same result -- I get the whole bunch instead of the filtered list.
    – Ilonpilaaja
    Nov 19 at 0:51
















("2018-11-17") is not a value except a name. I suggest changing your database structure.
– Kristofer
Nov 18 at 22:57




("2018-11-17") is not a value except a name. I suggest changing your database structure.
– Kristofer
Nov 18 at 22:57












check the database rules if it's not returning any data it has happened with me a lot that i forgot to edit database rules or when i create new node i forget to define the rules and if it is ruteurning you data then just show a bit more code so that it can be understood whats wrong
– Har Kal
Nov 18 at 23:02




check the database rules if it's not returning any data it has happened with me a lot that i forgot to edit database rules or when i create new node i forget to define the rules and if it is ruteurning you data then just show a bit more code so that it can be understood whats wrong
– Har Kal
Nov 18 at 23:02




1




1




the dates are keys here. why are you ordering by value? it should be orderByKey
– Reza Nasiri
Nov 18 at 23:23




the dates are keys here. why are you ordering by value? it should be orderByKey
– Reza Nasiri
Nov 18 at 23:23












@RezaNasiri: I did try orderByKey, same result -- I get the whole bunch instead of the filtered list.
– Ilonpilaaja
Nov 19 at 0:51




@RezaNasiri: I did try orderByKey, same result -- I get the whole bunch instead of the filtered list.
– Ilonpilaaja
Nov 19 at 0:51












1 Answer
1






active

oldest

votes

















up vote
3
down vote













You shouldn't be using a query to grab that key. Queries are used if you want a list returned, or if you don't know the exact path you're trying to reach.



As you know the uid and the date you can query the object directly.



JavaScript:



getMealsRefForUser(userId, date) {
return firebase.database().ref(`/mealsOf/${userId}/${date}`);
}


Android:



DatabaseReference root = FirebaseDatabase.getInstance().getReference("mealsOf");
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
return root.child(uid).child("2018-11-17");


Otherwise if you want to query you should use the startAt or endAt methods.



JavaScript:



getMealsRefForUser(userId, startDate) {
return firebase.database().ref(`/mealsOf/${userId}`).orderByKey().startAt(startDate);
}


Android:



return root.orderByKey().startAt("2018-11-17");





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53366220%2ffirebase-filtering-ordering-by-value-key%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    3
    down vote













    You shouldn't be using a query to grab that key. Queries are used if you want a list returned, or if you don't know the exact path you're trying to reach.



    As you know the uid and the date you can query the object directly.



    JavaScript:



    getMealsRefForUser(userId, date) {
    return firebase.database().ref(`/mealsOf/${userId}/${date}`);
    }


    Android:



    DatabaseReference root = FirebaseDatabase.getInstance().getReference("mealsOf");
    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    return root.child(uid).child("2018-11-17");


    Otherwise if you want to query you should use the startAt or endAt methods.



    JavaScript:



    getMealsRefForUser(userId, startDate) {
    return firebase.database().ref(`/mealsOf/${userId}`).orderByKey().startAt(startDate);
    }


    Android:



    return root.orderByKey().startAt("2018-11-17");





    share|improve this answer



























      up vote
      3
      down vote













      You shouldn't be using a query to grab that key. Queries are used if you want a list returned, or if you don't know the exact path you're trying to reach.



      As you know the uid and the date you can query the object directly.



      JavaScript:



      getMealsRefForUser(userId, date) {
      return firebase.database().ref(`/mealsOf/${userId}/${date}`);
      }


      Android:



      DatabaseReference root = FirebaseDatabase.getInstance().getReference("mealsOf");
      String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
      return root.child(uid).child("2018-11-17");


      Otherwise if you want to query you should use the startAt or endAt methods.



      JavaScript:



      getMealsRefForUser(userId, startDate) {
      return firebase.database().ref(`/mealsOf/${userId}`).orderByKey().startAt(startDate);
      }


      Android:



      return root.orderByKey().startAt("2018-11-17");





      share|improve this answer

























        up vote
        3
        down vote










        up vote
        3
        down vote









        You shouldn't be using a query to grab that key. Queries are used if you want a list returned, or if you don't know the exact path you're trying to reach.



        As you know the uid and the date you can query the object directly.



        JavaScript:



        getMealsRefForUser(userId, date) {
        return firebase.database().ref(`/mealsOf/${userId}/${date}`);
        }


        Android:



        DatabaseReference root = FirebaseDatabase.getInstance().getReference("mealsOf");
        String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
        return root.child(uid).child("2018-11-17");


        Otherwise if you want to query you should use the startAt or endAt methods.



        JavaScript:



        getMealsRefForUser(userId, startDate) {
        return firebase.database().ref(`/mealsOf/${userId}`).orderByKey().startAt(startDate);
        }


        Android:



        return root.orderByKey().startAt("2018-11-17");





        share|improve this answer














        You shouldn't be using a query to grab that key. Queries are used if you want a list returned, or if you don't know the exact path you're trying to reach.



        As you know the uid and the date you can query the object directly.



        JavaScript:



        getMealsRefForUser(userId, date) {
        return firebase.database().ref(`/mealsOf/${userId}/${date}`);
        }


        Android:



        DatabaseReference root = FirebaseDatabase.getInstance().getReference("mealsOf");
        String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
        return root.child(uid).child("2018-11-17");


        Otherwise if you want to query you should use the startAt or endAt methods.



        JavaScript:



        getMealsRefForUser(userId, startDate) {
        return firebase.database().ref(`/mealsOf/${userId}`).orderByKey().startAt(startDate);
        }


        Android:



        return root.orderByKey().startAt("2018-11-17");






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 19 at 3:53









        Frank van Puffelen

        221k25362387




        221k25362387










        answered Nov 19 at 1:09









        sketchthat

        1,7721818




        1,7721818






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53366220%2ffirebase-filtering-ordering-by-value-key%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Costa Masnaga

            Fotorealismo

            Sidney Franklin