I have a database substructure where I keep a count of the number of reports assigned to each admin
The database substructure looks like this
ReportCount
uuid string1: count1
uuid string2: count2
uuid string3: count3
I wish to retrieve this information using
firebase.database().ref('ReportCount').orderByValue().on("value", <Some Function>)
I want to do this to be able to figure out which admin has the least number of reports so a new report can be assigned to that admin.
However, when I use orderByValue, I see that the data retrieved is not ordered in ascending nor descending order of count values.
What is the issue here?
If you need to get the admin with least number of tasks on hand then you can just use the limitToFirstmethod:
firebase.database().ref("/ReportCount").orderByValue().limitToFirst(1).once("value").then((snapshot) => {
console.log(user.key, user.val())
})
If you are fetching all the admins and the data is not ordered, that is your browser as answered here.
If you run a loop directly on a snapshot as shown, the data will be logged in the order:
firebase.database().ref("/ReportCount").orderByValue().once("value").then((snapshot) => {
snapshot.forEach((user) => {
console.log(user.key, user.val())
})
})
Related
How to check the last record of a user in supabase. I would only need by means of the user ID to find his last record "date" in a descending way
I have something like the following, but this would just sort the table and I really don't want to bring it all just the most recent dates. I am working on this in nodejs with express and I am using the #supabase/supabase-js library for auth with supabase
Does anyone know how?
const { data, error } = await supabase.from('activity-historic-tracked').select('*').in('user_id', user_ids).order('date', { ascending: false })
I made the query in supabase using sql with DISTINC ON to return only different values because I only want to list the different values and not bring repeated values and at the end ordering them descendingly
select distinct on (user_id) user_id, date
from "activity-historic-tracked"
order by user_id, date desc;
According to what I was reading in this question rpc function, doing something like this could be done using views or supabase stored procedures, but how is it done?
Please help me
As mentioned in the other SO answer you linked, you can create a view or a rpc function. To create a view you would use the SQL editor in the Supabase Dashboard with the following:
CREATE VIEW view_name AS
SELECT DISTINCT on (user_id) user_id, date
FROM "activity-historic-tracked"
ORDER BY user_id, date DESC;
And now you would use this with the supabase-js library just like you would with a normal table.
await supabase.from('view_name').select('*')
If you were to go the .rpc function route, you would call it via that method on the supabase-js library.
I am trying to fetch data from firebase from messages table having a column 'email' and email equal to suppose "x#gmail.com" and "y#gmail.com". I need to fetch data if email equals to any of the two, but the query which i am using seems to be wrong.
also the messages need to sorted by time which is working.
var ref = db.collection('messages').orderBy('timestamp','desc')
var ref2 = ref.orderByChild('email').equalTo('x#gmail.com','y#gmail.com')
ref2.onSnapshot(snapshot => {setMessages(snapshot.docs.map(doc => ({id: doc.id, message : doc.data()})))});
Assuming you're using Firestore, what you want is an IN query. This allows you to specify up to 10 email addressses:
db.collection('messages')
.orderBy('timestamp','desc')
.where('email', 'in', ['x#gmail.com','y#gmail.com'])
For more on this, see the Firestore documentation on in, not-in, and array-contains-any conditions.
I currently have the following node:
Basically what I want is to search the registry by the uid parameter. What I can not understand is that they tell me that I should not do it by means of a query, so what would be the other way? I have tried with the following:
firebase
.database()
.ref('nuevosUsuario')
.child(user.uid)
.once('value')
.then(snapshot =>
console.log(snapshot.val())
);
pero me imprime en consola null
Thank you in advance, I'm new to firebase.
You JSON structure stores user information, where it stores the information for each user under a so-called push ID (a key generated by calling push() or childByAutoId()). You're trying to query this structure to find the user based on their UID, which is stored in a property for each user. The only way to do this is by using a database query, like:
firebase.database()
.ref('nuevosUsuario')
.orderByChild("uid")
.child(user.uid)
.once('value')
.then(snapshot => {
snapshot.forEach(userSnapshot => {
console.log(snapshot.val())
});
});
You need to perform a loop here, since there may be multiple nodes that have the correct value for their UID property.
If there can logically be only one node for each user under nuevosUsuario, it is better to store the user information under the user's UID as a key, instead of using a push ID.
So you'd get a structure like:
"nuevosUsuario": {
"SYFW1u808weaGEf3fW...": {
"appellido": "PRUEBA",
"correo": "..."
...
}
}
This has a few advantages:
There can only be one child node for each user, since keys are by definition unique in a collection.
You can now get the user given their UID without a query, which is both faster and simpler in code. As in: the code in your question would work for this structure.
I have the following query:
get invitations() {
return this.firestore.colWithIds$(`users/${this.authProvider.currentUserId}/meetings`, (ref) => {
return ref
.where(`participants.${this.authProvider.currentUserId}.invitation`, '==', 'pending')
.orderBy('createdAt', 'desc')
});
}
Everytime Firebase will generate an error that says: This query required an index and generates a link with the currentUserId in it. I add it to the console and everything works as expected..
However, this seems a bit too manual to maintain when users are registering. How can I generate a index that is dynamic and does not require manual entry every time a new user downloads my app?
The query you want to do, in the general case, is not possible in Cloud Firestore with your data structure.
You will quickly run into the limit of 200 composite indexes per database, probably around your 200th user:
https://firebase.google.com/docs/firestore/quotas#indexes
In Firebase Firestore, I want to use orderBy twice. Do I need to create an index to speed up the query?
For example:
Query query = fsDB.collection("users").document(currentUID).collection("received_messages")
.orderBy("messageSeen").orderBy("date");
There is no automatic Error message that shows up like when using ranges or "where".
Structure looks like:
received_messages
date: 01/02/99
messageSeen: true
from: keuajopdf315
Should I put an index on the collection "received messages" and the "messageSeen" and "date" fields to speed up the query?
When I try to run a query with two orderBy() clauses, I get an error:
The query requires an index. You can create it here: ...
After adding the index that is linked in the error message, I can then retrieve the documents ordered-by-state-then-by-index. See my working jsbin here: https://jsbin.com/rewujav/edit?js,console
docs.orderBy("state").orderBy("index").get().then(function(snapshot) {
snapshot.forEach((doc) => {
console.log(doc.id+": state="+doc.data().state+" index="+doc.data().index);
})
})