I have my database as shown below:
Note that dev-user-messages
is at root level. Now I am trying to query it like this:
get(query(ref(db, path), orderByChild('lastModified'))).then((snapshot) => {
if (snapshot.exists()) {
const res = snapshot.val();
console.log(res);
}
});
However no matter which way I order it, I tried using limitToLast
and limitToFirst
as well but all of them return the response always in the order of keys (i.e. a,b,c,d):
{
"a": {
"lastModified": 1
},
"b": {
"lastModified": 2
},
"c": {
"lastModified": 10
},
"d": {
"lastModified": 5
}
}
Am I doing something wrong here?
Edit:
As suggested by Frank and referring to the following post, I updated my query to be like this:
React.useEffect(() => {
const path = formMessagesPath(process.env.NODE_ENV === 'production');
console.log(path);
get(
query(ref(db, path), orderByChild('lastModified'), limitToLast(limit))
).then((snapshot) => {
if (snapshot.exists()) {
console.log(snapshot.forEach((item) => console.log(item.val())));
}
});
}, []);
However changing this line:
get(
query(ref(db, path), orderByChild('lastModified'), limitToLast(limit))
)
Output:
get(
query(ref(db, path), orderByChild('lastModified'), limitToFirst(limit))
)
yields the same result:
Output:
I understand invoking .val()
resets the order but what is the problem now when I use forEach
?
Edit 2: Okay, now I think I fully understand this, so my question is majorly how can I change the order of sorting. (Currently it seems to be ascending, how to make it descending?):
Desired outcome:
Data:
{
"a": {
"lastModified": 1
},
"b": {
"lastModified": 2
},
"c": {
"lastModified": 10
},
"d": {
"lastModified": 5
}
}
I would want two cases:
1.fetch last N child (ordered By lastModified key in descending order): [10,5,2] 2. Fetch last N child (ordered By lastModified key in ascending order): [2,5,10]
My understanding is orderBy('lastModified') orders data as:
[1,2,5,10]
and limitToLast(100) would return the data as:
[1,2,5,10]
However, when I do limitToFirst(100), the data remains the same:
[1,2,5,10]
Now what if I want it to be ordered in descending way first and then apply limitToFirst
or limitToLast
based upon my requirement?