Querying firebase database to retrieve user name - javascript

I am working on firebase for the first time. I am confused in querying the database. I have two objects on the database, one is the Auth and second one is the Chats. In Auths I have number of UID(user id) nodes, each of these nodes have their respective username. What I am trying to do is, I want to query that Auth object and get all the usernames which is equal to the one I take from a user through input box. In my sql it will be simple as SELECT * FROM auth WHERE username = userInputValue. I need same query like this, Below is what I have done so far.
var _firbaseDB = firebase.database(),
_firebaseAuthRef = _firbaseDB.ref("Auth/");
$("body").on("submit",".search-from",function(e){
e.preventDefault();
var ev = e.target,
_allUsers = $(ev).serializeArray()
_user = _allUsers[0].value;
_firebaseAuthRef.equalTo(_user).on("child_added",function(res){
console.log(res.val());
})
})

You were almost there. What's missing is that you need to specify which attribute you're querying on:
_firebaseAuthRef.orderByChild("n").equalTo(_user).on("child_‌​added",function(res)‌​{
console.log(res.val());
})
More info on the Firebase Database Documentation.

Related

How to get value from firebase without the snapshot key [JS]

Im trying to make friends system but in invite accept i have to delete invite of a guy in his list but i cant do it without the key.
How do i get the snapshot key by value (in this case uid) in database?
Firebase Realtime Database queries work on single path, and then order/filter on a value at a fixed path under each direct child node. In your case, if you know whether the user is active or pending, you can find a specific value with:
const ref = firebase.database().ref("friends");
const query = ref.child("active").orderByValue().equalTo("JrvFaTDGV6TnkZq6uGMNICxwGwo2")
const results = query.get();
results.forEach((snapshot) => {
console.log(`Found value ${snapshot.val()} under key ${snapshot.key}`)
})
There is no way to perform the same query across both active and pending nodes at the same time, so you will either have to perform a separate query for each of those, or change your data model to have a single flat list of users. In that case you'll likely store the status and UID for each user as a child property, and use orderByChild("uid").
Also note that using push IDs as keys seems an antipattern here, as my guess is that each UID should only have one status. A better data model for this is:
friends: {
"JrvFaTDGV6TnkZq6uGMNICxwGwo2": {
status: "active"
}
}

how to check if value exists in realtime database firebase

I have created a realtime database on firebase and having no issues adding and removing data in tables etc.
I currently have it setup like this:
So my goal is to check if a given value is inside my database currently.
for example, I would like to check if 'max' is currently a username in my database.
var data = db.ref('loginInfo/');
data.on('value', function(snapshot) {
_this.users = snapshot.val()
});
That is how I get all the values, it is saved into _this.users
(How do i check if a value is inside this object, i am making a login program)
if i console.log the object, this is what I see:
image
If you want to check if a child node exists under loginInfo where the username property has a value of max, you can use the following query for that:
var ref = db.ref('loginInfo/');
var query = ref.orderByChild('username').equalTo('max');
query.once('value', function(snapshot) {
console.log(snapshot.exists());
});
I'd also recommend reading the Firebase documentation on queries, as there are many more options.

Trying to check for a certain field inside a firebase firestore document but struggling with the logic behind it

So I am using this currently to check and see if a doc exists for a user
let user = firebase.auth().currentUser;
let userInfo = db.collection("stripe_customers").doc(user.uid);
and then if it does, it runs a script I want
userInfo.get().then(function (doc) {
if (doc.exists) {
However, instead of checking for a specific doc, I need to try and check for a field value inside some documents.
For example I have a collection called "stripe_customers" > that has a document per user via their UID > then inside the document is the collection "charges" > then inside "charges" is a document under a random string of numbers and letters "89nzVNrfQCOVqogDaGvo" for example that is generated by stripe for their charge after they purchase (there may be multiple of these if they have an older charge which is why I need to find the most recent one) > then inside the most recent charge document, I need to check for the field "status" and that is has the value "succeeded". That way I can check to see who has a succeeded payment and if they do it will run the script I want. I am just so confused on how to achieve this. I know how to do basic queries but this is somewhat complex. I need to be able to make sure the current UID has that field with that value so I can see if the current UID paid or not and if they did the script runs, which sets a custom claim.
Here is a visual of my db storage flow for what im trying to do so its easier to understand https://imgur.com/a/NE1x6sU
So, you want to get the most recent document in a charges (sub)collection based on a created field which contains a timestamp value, and check the value of the status field of this doc.
The following should do the trick:
const user = firebase.auth().currentUser;
const subCollRef = db.collection("stripe_customers").doc(user.uid).collection("charges");
const query = subCollRef.orderBy('created', 'desc').limit(1);
query.get()
.then(snapshot => {
if (snapshot.size > 0 && snapshot.docs[0].data().status === "succeeded") {
//payment was succeeded, you can "run your script"
});
})
.catch(err => {
console.log('Error getting documents', err);
});

Retrieve count data from Firebase like MySQL

When trying to pull data from a MySQL database, I can do something like:
SELECT * FROM users ORDER BY id WHERE vehicle = car
That should get me all the users that drives a car and not show users that drives a motorcycle for instance.
Is there something like this for Firebase? I can only retrieve specific data from one user?
My firebase database is like this: user -> user info (name, age, vehicle etc..)
I want to query every user that drives a car and display them in a row. How do I do that?
I have tried the following, but I didn't succeed with what I tried to do, since after users the users id is the next child. Is there a way to query past that?
var recents = firebase.database().child('users').orderByChild('department').equalTo(department);
recents.on('child_added', function(snapshot) {
var countOfUserInDepartment = snapshot.count;
document.querySelector("#cphCount").innerHTML = countOfUserInDepartment;
});
There are no count queries (nor other aggregation queries) in the Firebase Database. Your options are:
Retrieve all data matching your query and count client-side
Keep a separate count-node that you update whenever you add/remove items.
For #2 you may find it convenient to use Cloud Functions, for which there an an example of keeping such a counter.
Also see:
Firebase count group by
Database-style Queries with Firebase
In Firebase, is there a way to get the number of children of a node without loading all the node data?
How to get size of an element/list in Firebase without get it all?

Firebase set new unique ID

I'm new to firebase and practicing creating a ToDo application. So far this is my code:
Code:
var getUserRef = firebase.database().ref('users');
getUserRef.on('child_added', function(data) {
var name = data.child("name").val();
var email = data.child("email").val();
$('#loadData').append(`<tr><td>${name}</td><td>${email}</td><td>Edit Remove</td></tr>`);
});
function addUser() {
var database = firebase.database();
var name = $('#name').val();
var email = $('#email').val();
var newID = 4; // How can this be incremented?
database.ref('users/' + newID).set({
name: name,
email: email
});
}
Data Structure:
As you can see, everytime I create a new user, I am manually changing the newID variable.
My problem is I don't want to change it everytime I insert a new user. I want it to aumotically increment or generate a random unique ID.
Is there a way to do this in google firebase?
What you have here is a list of items. If you have such a list, it is common to use Firebase's push() method to add new items to it. This will generate a chronological key that is guaranteed to be unique across all clients, even in cases where some clients may have temporarily lost their network connection while they're adding data. These push IDs are not as readable as your array indices, but they are the recommended way of adding items to a list.
That said; you're not dealing with any list here, it is a list of users. If you're using Firebase Authentication to manage the user accounts and handle authentication, the users come with a build in id called uid. In such a case it makes more sense to store the items under their natural key, so under their uid in this case.
Yes there is.
Here is a code from firebase docs of an example of Push().
var messageListRef = firebase.database().ref('message_list');
var newMessageRef = messageListRef.push();
newMessageRef.set({
'user_id': 'ada',
'text': 'Example of text.'
});
You can find all this information about other methods here :
https://firebase.google.com/docs/reference/js/firebase.database.Reference

Categories

Resources