How to write data into a specific location Firebase Web

456 views Asked by At

I want to write data into a specific location in the database. Let's say, I have a couple of users in the database. Each of them has their own personal information, including their e-mails. I want to find the user based on the e-mail, that's to say by using his e-mail (but I don't know exactly whose e-mail it is, but whoever it is do something with that user's information). To be more visible, here is my database sample.

enter image description here

Now, while working on one of my javascript files, when the user let's say name1 changes his name, I update my object in javascript and want to replace the whole object under ID "-LEp2F2fSDUt94SRU0cx". To cut short, I want to write this updated object in the path ("Users/-LEp2F2fSDUt94SRU0cx") without doing it by hand and just "knowing" the e-mail. So the logic is "Go find the user with the e-mail "[email protected]" and replace the whole object with his new updated object". I tried to use orderByChild("Email").equalTo("[email protected]").set(updated_object), but this syntax does not work I guess. Hopefully I could explain myself.

2

There are 2 answers

2
Stradosphere On

The first part is the query, that is separate from the post to update. This part is the query to get the value:

ref.child('users').orderByChild("Email").equalTo("[email protected]")

To update, you need to do something like this once you have the user id from the query result:

ref.child('users').child(userId).child("Email").update(newValue);
0
Ronnie Royston On

firebase.database.Query

A Query sorts and filters the data at a Database location so only a subset of the child data is included. This can be used to order a collection of data by some attribute (for example, height of dinosaurs) as well as to restrict a large list of items (for example, chat messages) down to a number suitable for synchronizing to the client. Queries are created by chaining together one or more of the filter methods defined here.

// Find all dinosaurs whose height is exactly 25 meters.
var ref = firebase.database().ref("dinosaurs");
ref.orderByChild("height").equalTo(25).on("child_added", function(snapshot) {
  console.log(snapshot.key);
});