Firebase database modeling: n:n relations

Asked

Viewed 849 times

4

I’m studying firebase that uses Nosql and I came up with a question when watching this video: Converting SQL Structures into Firebase Structures - Firebase Database for SQL Developers #2

In it the author creates a structure like this:

inserir a descrição da imagem aqui

Blz...with this structure it would be very easy to return all the participants of a given event just going through the eventAttendees node.

But what if I want to know all events that a certain user participates in. How would I do? If I create another usersAttendees node I could do this by saving users and within each user the events it participates in.

But then we have a problem: data duplication. If there is a modification, say, if I remove an event from the David user, I will have to remove it from both nodes : eventAttendees and usersAttendees.

This would be easily done using SQL modeling as in the photo but the goal here is to do using Nosql: Estrutura em SQL

So my question is, what’s the best way to model this in Nosql to avoid this kind of problem?

EDIT: I realized that this problem persists for any relationship n to n. So specifying further, my doubt would be how to make n to n relations with Nosql in the best possible way?

1 answer

0

But what if I want to know all events that a certain user participates. As I would?

You can make a query without having to change its structure. For example, to see all the events David participates in:

var eventAttendeesRef = firebase.database() .ref().child("eventAttendees");
eventAttendeesRef.orderByChild('1').equalTo('David').once('value', function(dataSnapshot){
    dataSnapshot.forEach(function(snapshot){
        var eventoID = snapshot.getKey();
        console.log('O David participa do evento com ID: '+eventoID);
    });
});

How to make n to n relations with Nosql in the best possible way?

Nosql doesn’t have a standard way of making n to n relationships. As you may have seen in this series of Youtube videos, you have to structure your data according to your View. Always look for a structure that reduces the number of queries needed to get a data. Even if you have to duplicate some data in some situations.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.