Finding a register by field - javascript

I have my database in firebase as you can see here https://snag.gy/bhopOk.jpg
The user scans a product and brings you the number of this product, which is put in an input, then when you click on search you must bring the description and the value of that item and show it somewhere in the front
This is my frontend
How would the function or query be so that when the person click on search brings me the requested data? I know it's a simple query but I do not have it very clear I'm new to ionic
I tried to do this to see if I returned something in the console but nothing
findproduct(){
var ref = firebase.database().ref("/productos/");
ref.orderByChild("Producto").equalTo(1706).on("child_added", function(snapshot) {
console.log(snapshot.key);
});
}

You can write your function as follows. However, note that query.once() is asynchronous and returns a Promise. So you have to take that into account when you call it.
findproduct(productID) {
var query = firebase.database().ref("productos").orderByChild("Producto").equalTo(productID);
query.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
console.log(childKey);
var childData = childSnapshot.val();
console.log(childData);
});
});
}
When you just want to query once, use the once() method: it "Listens for exactly one event of the specified event type ('alue' in this case), and then stops listening". See the documentation here.
When using the on() method, you are constantly listening to data changes at the location defined by the query. See the doc here.

Related

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 fix the problems arising from asynchronous code in javascript

I am new in database systems and what I am trying to do is to check whether the e-mail entered by the user during login exists in the database or not. I use Firebase Databse. So, the code I have written is this:
function login(){
var e_mail = document.getElementById("e-mail").value;
rootRef = firebase.database().ref();
rootRef.orderByChild("E_mail").on("child_added", function(snapshot){
lst.push(snapshot.val().E_mail);
//console.log(lst);
})
console.log(lst);
}
let lst = [];
login_btn.onclick = function() {login()};
I want to fetch all e-mails from the database, add them in the list and then loop through that list. Maybe this is not the best way, but that's what I'm working on. I could also just say if (snapshot.val().E_mail == e_mail){alert("there is such a user");}but the problem I have encountered and want to deal with is not that, it's the "callback" function inside login function. When I console the list in the outer function it shows an empty list as it does not run the inner function until it is done with the outer one. I understand this. But how can I avoid or fix this. I want to get the full list of e-mails to be able to loop through it then. Also, I don't know how to end the "loop" in Firebase, because it is sort of looping when it gets the e-mails. So I would like to stop at the moment when it finds a matching e-mail.
You're downloading all users to see if one name exists already. That is a waste of bandwidth.
Instead you should use a query to match the email you're looking for, and only read that node:
rootRef.orderByChild("E_mail").equalTo(e_mail).once("value", function(snapshot){
if (snapshot.exists()) {
// A node with the requested email already exists
}
})
In general, if you need to process all nodes, you'll want to use a value event, which executes for all matching nodes at once. So to get all users from the database, add them to a list, and then do something with that list:
rootRef.orderByChild("E_mail").once("value", function(snapshot){
var list = [];
snapshot.forEach(function(childSnapshot) {
list.push(childSnapshot.val());
});
console.log(list); // this will display the populated array
})
Note that you won't be able to access the list outside of the callback. Even if you declare the variable outside of the callback, it will only be properly populated inside the callback. See Xufox' comment for a link explaining why that is.

Data is not added to existing node in database

I have been trying to add data to my database without any luck.
In my code i have made a button when click, it will add data to my users database but it will not add it to the user but it just add the data outside like this:
is it because you cant add data when you have use the createUserWithEmailAndPassword() function?
Can anyone please show me how it is done?
btn.addEventListener("click", function()
{
firebase.auth().onAuthStateChanged(function(user)
{
if (user)
{
var massage = inputText.value;
var ref = database.ref("Users");
var data = {
display: massage
}
ref.push(data);
}
});
});
Whenever you call push() Firebase generates a new unique ID. So to add the new data to the existing node, you should not call push. Instead you need to find a reference to the existing node for that user.
The easiest (and by far most common) way to do this, is to store the user data under the UID of each user.
Users
kHD...NoS
username: "bob"
Also note that there's no reason to put this type of onAuthStateChange listener inside a button click handler. Just attach it from the top-level JavaScript and it will trigger whenever the user signs in or when their auth state changes in any other way.
Alternatively, if the code really must run in response to the button click, there's no real use for a auth state listener and you can just check firebase.auth().currentUser:
btn.addEventListener("click", function()
{
if (firebase.auth().currentUser)
{
var message = inputText.value;
var ref = database.ref("Users");
var data = {
display: massage
}
ref.child(firebase.auth().currentUser.uid).update(data);
}
}
Your code seems correct if you want to insert a new entry in Firebase database (just like your screenshot shows).
But, if you really want to sign up a new user, then you should be using firebase.auth().createUserWithEmailAndPassword() instead.
Finally, if you really want to update an existing node, see Frank response above ;-)
try this. you can change update to set. In your case something like
demo.update("users/KIK...fuA","display","my message");
//REVEALED METHOD TO ADD NODES WITH DATA TO REALTIME DATABASE
//eg, demo.update('mynode','myKey','myValue')
var demo = (function() {
var pub = {};
pub.update = function (node,key,value){
var ref = firebase.database().ref('/');
var obj = {};
obj[key] = value;
ref.child(node).update(obj)
.then(function() {
console.log('Update Ran Successfully');
});
}
//API
return pub;
}());

Search inside objects javascript

I'm experimenting on login with firebase. I can make an account, and it'll store additional information too. The problem is retrieving this information.
I can get it using:
usersRef.on("value", function(snapshot) {
console.log(snapshot.val())
}, function (errorObject) {...});
When I do this I get two things (because I have two accounts):
-JrrzEOqZQU0HVeYVXCm: Object, has uid: "simplelogin:21" inside of it
-JrrzgOgQY2z6tNYN0BY: Object, has uid: "simplelogin:22" inside of it
Inside of the second object is the info that I need:
I received simplelogin:22 from the login.
Is there a way I can search inside of the objects to their uid, and get the rest of the information stored inside of that object?
Here's a fiddle
var thisAuthData = authData.uid;
//console.log(authData)
var usersRef = new Firebase("https://fiery-heat-xxx.firebaseio.com/users");
usersRef.on("value", function(snapshot) {
for(var amount in snapshot.val()){
console.log(snapshot.val()[amount].uid);
//here some if statement thingy's to check with your authData but you can do that yourself I guess ;)
}

Firebase field delayed update

I have a Firebase with a users reference, which has a field user_id.
([Firebase]/[app]/users/user_id)
I insert a user & assign a user_id. However, when I read the value of user_id from userRef (a reference to users), it does not read it the first time. Subsequent reads work perfectly fine.
Using the debugger, I can see that when the user is created, a user_id is assigned. It seems like my first call refreshes the Firebase reference, so that subsequent calls are now seeing the udpated Firebase (I don't think that is what it is - that is just how it appears).
This is my code to read the value of user_id:
var userID = 0;
userRef.on('value', function(snapshot) {
userID = snapshot.val().user_id;
});
alert(userID);
The first time, the alert shows 0. Every time after that, it shows the correct value.
To make the problem even stranger, I also have a games reference with a game_id, created in the same way as user. But my read on game_id (in the exact same way & at the same time) works every time.
Any ideas?
The issue here is that .on() doesn't (in general) trigger your callback function immediately. In particular, the first time you do a .on() at a location, Firebase has to go ask the server for the current value, wait for the response, and THEN call your callback. And it does this all asynchronously.
The way your code is currently written, "alert(userID);" is being run before your callback code ("userID = snapshot.val().user_id;") so it always reports 0 the first time. The simple fix is to move the alert() inside your callback:
var userID = 0;
userRef.on('value', function(snapshot) {
userID = snapshot.val().user_id;
alert(userID);
});
Here's a common methodology to wait on two callbacks, using using jQuery's Promise model and once:
var userID = 0;
// sends a callback to fx where the results can be stored
function defer( fx ) {
return function() {
var deferred = $.Deferred();
fx( function(snapshot) { deferred.resolve(snapshot.val(); } );
return deferred.promise();
}
}
$.when( // wait for both actions to complete
defer( function(callback) { userRef.once('value', callback) }),
defer( function(callback) { widgetRef.once('value', callback) })
).then( function(values) {
// both deferreds are done now
// and values contains an array with the snapshot.val() from each call
console.log(values);
});

Categories

Resources