Optimize Firebase database design

760 views Asked by At

I am having trouble designing the database of my app. In the app users are allowed to create jobs and then using GeoFire I find people nearby.

This is my design for the jobs so far:

enter image description here

As you can see there are the users and then the workers. After pushing the new job to the users Unique ID (UID) under serviceUsers, I then use geoFire to find the workerUsers that are nearby. I then push the jobs into the UID's of the workerUsers.

Now here are my questions:

I am basically creating copies of these jobs. Once for the person who created it (under serviceUsers) and once for every nearby workerUsers. Is this inefficient? Should I rather pass some kind of pointer instead of the whole job object to the nearby users?

And here for the more important question: If the design is fine as it is, how would I go on about when the creator of the job deletes it? I would then need to find each job in workerUsers and delete the job with the jobs UID. Does Firebase support queries for this?

Thank you very much in advance!

1

There are 1 answers

3
Michał Pietraszko On BEST ANSWER

I am basically creating copies of these jobs. Once for the person who created it (under serviceUsers) and once for every nearby workerUsers. Is this inefficient? Should I rather pass some kind of pointer instead of the whole job object to the nearby users?

Every job should have a UUID which can act as a "pointer" (I'd rather call it a key). Then every user should include a job UUID, not a whole copy, so you can refer to it. I won't completely replicate your use case, but you should get an idea.

{
  users: {
   exampleUserId: {
      jobs: ['exampleUUID']
    }
  },
  jobs: {
   exampleUUID: {
     name: 'awesome job'
   }
  }
}

If the design is fine as it is, how would I go on about when the creator of the job deletes it? I would then need to find each job in workerUsers and delete the job with the jobs UID. Does Firebase support queries for this?

It does support it, but you should implement my suggestion from above to do it in a sane way. After this, you can create a cloud function whose job should sound like this: "When a job with given UUID is removed, then go through every user and remove a reference to it if it exists"

exports.checkReferences = functions.database.ref('/jobs/{uuid}').onWrite(event => {
  // check information here

  if (!event.data.val()) {
    // job was removed! get its uuid and iterate through users and remove the uuid from them
  }
});