简体   繁体   中英

Firebase data structuring - accessing jobIDs for each user

In my database, I currently have two kinds of objects, users and jobs. I am already storing userIDs in jobs. Do I also need to store jobIDs in each user?

A typical user :

 "-JqzUjcOfddBNd_HtjKb" : {
  "contact" : {
    "-JqzWcIyD77ZwatEKALp" : {
      "email" : "someguy@yahoo.com"
    },
    "-JqzWrtyni3ZGOKooNF7" : {
      "email" : "someguy@outlook.com"
    }
  },
  "country" : "234",
  "cv" : "https://linktourl.com",
  "dateAdded" : 1433436879708,
  "ethnicity" : "0",
  "firstName" : "John",
  "lastName" : "Smith",
  "notes" : {
    "-JqzhvtNcueUsPr8xwh8" : {
      "date" : 1433440599702,
      "user" : "iwrotethisnote@example.com",
      "value" : "interested in job; need to interview"
    }
  },
  "roles" : [ true ]
},

And a typical job :

"-Jqz5mOr-DmLcxmTVRPi" : {
  "age" : [ "2" ],
  "city" : "0",
  "clientID" : "-Jqz7goZC76vl94VT0dq",
  "dateModified" : 1433431226687,
  "longDesc" : "Teacher should have experience",
  "notes" : {
    "-Jqz6SO74OJOESwOVfkG" : {
      "date" : 1433430513294,
      "notevalue" : "bill spoke with her",
      "userid" : "name@gmail.com"
    }
  },
  "schedule" : "Evening or weekend",
  "status" : "needDetail",
  "subjects" : {
    "15" : true,
    "42" : true
  },
  "title" : "She wants a native speaker"
},

As you can see, jobs have a field for clientID, which is a foreign key (so to speak) of a user's id. When I access a user's information, I want to know those jobs that they are associated with (ie for which they have supplied their client ID). How to do this in Firebase?

Should I:

  1. Update both objects, and keep an array of jobIDs in the client object?

  2. Query all jobs, then pass in those that have the user's ID as the client ID. Something like:

     // user controller var jobs = []; jobsRef.$on('value', function(snapshot) { snapshot.val().forEach(function(job) { if (job.clientID = $scope.userID) { jobs.push(job); } } } 

Option 1 makes the data redundant (which I guess is ok, because of the emphasis on denormalization), but it also makes it more likely to become out of sync, for example if one of the two updates I would be making fails.

Option 2 seems like it would run a lot slower.

You can use equalTo() of firebase query

var jobsRef = new Firebase();
jobsRef.orderByChild("clientID").equalTo($scope.userID)
.on("value", function(snapshot) {
  console.log(snapshot.key());
});

For more info, please check out Query.equalTo()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM