2

How would I structure my data in firebase to retrieve all posts that the current user has not commented on. I am very new to nosql and I can't seem to get my head out of a SQL way of structuring it.

This is my attempt at it:

Posts: {
 someUniqueId: {
   user: userid,
   content: "blah"
 }
}

Comments: {
 someCommentUniqueId: {
  comment: "ola",
  post: someUniqueId,
  user: userid
 }
}

Now if the above is correct, I have absolutely no idea how I would query this. Is it even possible in NOSQL?

Community
  • 1
  • 1
Jacub L
  • 21
  • 2

2 Answers2

2

Firebase does not have a mechanism to query for the absence of a value. See is it possible query data that are not equal to the specified condition?

In NoSQL you often end up modeling data for the queries that you need. So if you want to know which posts each user still can comment on, model that information in your JSON tree:

CommentablePosts_per_User
    $uid
        $postid: true

This type of structure is often called an index, since it allows you to efficiently look up the relevant $postid values for a given user. The process of extracting such indexes from the data is often called denormalization. For a (somewhat older) overview of this technique, see this Firebase blog post on denormalization.

I recommend this article as a good introduction to NoSQL data modeling.

Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

If I may suggest a couple of options:

Posts:
   someUniquePostId:
     user_id_0: false
     user_id_1: true
       comment: "dude, awesome post"
     user_id_2: false
     user_id_3: true
       comment: "wicked!"

drive space is cheap, so storing all the user id's within the post would allow you to easily select which posts user_id_0 has not commented on by query'ing for user_id_0: false.

Alternatively you could flip the logic

Posts:
   post_id_0:
     user_id_1: "dude, awesome post"
     user_id_3: "wicked"
   post_id_1:
     user_id_0: "meh"
     user_id_2: "sup?"
Users:
   user_id_0:
     no_posts:
       post_id_0: true
   user_id_1:
     no_posts:
       post_id_1: true

This would enable you to query which posts each user has not posted to: in this case, user_id_0 has not posted to post_id_0 and user_id_1 has not posted to post_id_1

Of course, depending on the situation, you can also lean on client logic to get the data you need. For example, if you only care about which posts a user didn't comment on yesterday, you could read query them by .value of yesterday and do a comparison in code to see if their user_id is a child of the post. Obviously avoiding this if the dataset is large.

Jay
  • 34,438
  • 18
  • 52
  • 81