0

I'm currently in the proccess of making a web application for a university project and I need some help in retrieving a value in the Firebase database. Here is the structure:

enter image description here

What im trying to do is see if a specific uid is present anywhere unfer the ref 'addresses'

this is my code:

var refAdd = firebase.database().ref().child('addresses');
refAdd.orderByChild("uid").equalTo(user.uid).once("value", function(snapshot){
  console.log("(snapshot) request found for " + snapshot.key);
    snapshot.forEach(function(child) {
        console.log("request found for " + child.key);
    });
});

So what I'm trying to do here is see if ther current user UID is present under 'addresses', if it is then log the push key value where it's located.

Anyone one have any idea on how to go about it?

0

1 Answer 1

1

The best approach would probably be to denormalize your data. That means that each time you write a "request" for a specific user under a specific "addresses" item you should also write, in another database node the "push" id of the "address" under the uid of the user.

In other words, based on your example you should have a database like:

- addresses
  + -LAPf7dNDU...
    + requests
       - ......
- addressesByUid
  - 9nras7IY.....   //You use the user uid as the key of this node
    - adressId: "-LAPf7dNDU..."  //The key of the address

In such a way your query will be much easier.

The only "difficulty"is the fact that you have to maintain the two nodes in sync. But this can be easily done with e.g. an set of writes like in the following example (from the doc):

  // Get a key for a new Post.
  var newPostKey = firebase.database().ref().child('posts').push().key;

  // Write the new post's data simultaneously in the posts list and the user's post list.
  var updates = {};
  updates['/posts/' + newPostKey] = postData;
  updates['/user-posts/' + uid + '/' + newPostKey] = postData;

  return firebase.database().ref().update(updates);

Finally, note that, if necessary, you could have several addressIDs under a user uid by doing something like

- addressesByUid
  + 9nras7IY.....   //You use the user uid as the key of this node
    - -LAPf7dNDU...: "true"  
    - -LUTTE66hf...: "true"  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.