0

I'm having trouble fetching data on firebase with complex structure. I have a structure like this:

place1: {
 visits: {
  user1: true,
  user2: true,
  user3: true,
  user4: true
 }
},
place2: {
 visits: {
  user1: true,
  user3: true,
  user4: true
 }
},
place3: {
 visits: {
  user2: true,
  user3: true,
  user4: true
 }
}

How do you query all the users that has been to all the places?

Thank you so much for your help!

AL.
  • 36,815
  • 10
  • 142
  • 281
pat3ck029
  • 263
  • 1
  • 7
  • 19

1 Answers1

1

Your current data structure allows you to efficiently fine all users that have been to a specific place. It does not allow you to efficiently query all places that a specific user has been to.

To allow that second query, you should add a second data structure:

user1: {
  place1: true,
  place2: true
},
user2: {
  place1: true,
},
user3: {
  place1: true,
  place3: true
},
user4: {
  place1: true,
  place2: true,
  place3: true,
  place4: true
}

With this additional structure (often called an inverted index) in place, you can find the places each user went to.

Since you now have two structures, you will need to ensure you add each visit to both places. A single multi-location update can accomplish that:

function recordVisitor(uid, placeid) {
  var updates = {};
  updates[`/userVisits/${uid}/${placeid}`] = true;
  updates[`placeVisitors/${placeid}/${uid}`] = true;
  firebase.database().ref().update(updates);
}

Also see my answer for a related use-case (querying items in categories) that also requires an inverted index: http://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807