Yeats
Yeats

Reputation: 2065

Do I always need to duplicate and nest data to refer to it in noSQL (Firebase)?

I haven't exactly worked with SQL a lot, but apparently enough to be gripped by its claws, because I'm rather at a loss on how to refer to things in noSQL.

Let's say I have a page displaying books, and then a feature where users can save any amount of books to their own personal libraries ("liking" them, essentially).

A book comprises parameters like author, title, amount of pages, synopsis, list of characters, etc.

In SQL I would need to set up a join table between books and users, but in noSQL (and specifically Firebase because that's what I'm starting with) there's no such thing and that leaves me puzzled. I have been warned to nest data, but here it seems necessary to nest books under users (or vice versa?) and have a lot of duplicated data.

This seems icky to me for several reasons. One is that it would require a lot of extra time to iterate over users, because their entire library would need to be iterated over as well. Second, I would need to duplicate a lot of data, because I want to display the books in their library in full, along with the synopsis and character lists, etc.

Do I actually need to make another segment, called library, where I list users and nest their books under them? Is that a valid approach?

Or have I missed something essential here? Can I actually refer to data as with a foreign key even in noSQL (including Firebase)?

Upvotes: 1

Views: 127

Answers (1)

MattDionis
MattDionis

Reputation: 3616

I ran into the same issues coming from a SQL background. The example structure below is a very high-level view of what your noSQL, in this case Firebase, may best look like:

- Firebase root
    - Users
        - $userId
            - name
            - email
            - books
                - $bookId
    - Books
        - $bookId
            - title
            - author

...and a very simple idea of how you'd access books:

var ref = new Firebase();
ref.child('Books').child($bookId).push({/* book info */});

In summary, those $userId and $bookId fields become very important to reference data throughout your app.

Upvotes: 2

Related Questions