Search code examples
javascriptfirebasevue.jsnosqldenormalization

Does Firebase send ALL the data under a given path?


I'm a little confused as to how much data is automatically fetched by Firebase and I'm having a hard time modeling data.

As I understand it, an authenticated user's ID is compared to the path; if the key is missing, the path is inaccessible. In addition, once a path is called, all of the data within it is accessed.

For instance, fetching /cart/<$uid>/<item> would also include $uid1, $uid, $uid3 ... $uidN, etc. So if I were to nest all of the data under /<$uid>, like:

/<$uid>/cart

/<$uid>/orders

/<$uid>/transactions

Does this mean that fetching /<$uid>/cart also returns all those other keys? What if I only call <$uid>?

If the structure is instead by cart/ or orders/ first, does this mean all the orders for all the users are fetched?

In other words, when a user logs in, I'd like to retrieve the contents of (using one of those "schemas") the cart:

// Fires onAuthStateChanged()
firebaseListener(function authStateChange(loggedIn, user) {
  if (store) {
    if (user) {
      store.dispatch('getShoppingCart', { uid: user.uid, currentCart: store.getters.cartItemList });
      store.dispatch('setUser', user);
    }
  }
})

getShoppingCart then runs something similar to:

let ref = db.ref('/cart/' + store.state.uid + '/')
ref.on('value', (snapshot) => {
  store.cart.concat(snapshot)
})

Solution

  • When a user logs in, you are retrieving the information of that user, so when you use uid, you are retrieving the id of that login user.

    When you use this ref('/cart/' + store.state.uid + '/') it will go to cart node first and then the uid of that user and not all userids who are under carts.

    You can also use once('value').then(function(snapshot) { which will only read the data once and not trigger again.