This is the current sample structure
Posts(Collection)
- post1Id : {
viewCount : 100,
likes : 45,
points : 190,
title : "Title",
postType : image/video
url : FileUrl,
createdOn : Timestamp,
createdBy : user20Id,
userName : name,
profilePic: url
}
Users(Collection)
- user1Id(Document):{
postsCount : 10,
userName : name,
profilePic : url
}
viewed(Collection)
- post1Id(Document):{
viewedTime : ""
}
- user2Id(Document)
The End goal is - I need to getPosts that the current user did not view and in points field descending order with paging.
What are the possible optimal solutions(like changing structure, cloud functions, multiple queries from client side)?
Seeing your database structure, I can say you're almost there. According to your comment, you are hosting under the following reference:
As documents, all the posts a user has seen and you want to get all the post that the user hasn't seen. Because there is no
!=
(not equal to) operator in Firestore nor aarrayNotContains()
function, the only option that you have is to create an extra database call for each post that you want to display and check if that particular post is already seen or not.To achieve this, first you need to add another property under your post object named
postId
, which will hold as String the actual post id. Now everytime you want to display the new posts, you should check if the post id already exist inviewed
collection or not. If it dons't exist, display that post in your desired view, otherwise don't. That's it.Edit: According to your comments:
Yes, for the first post to appear, two database calls are need, one to get post and second to see if it was or not seen.
No, only two calls, as explained above.
No, this is how NoSQL database work.
Not I'm aware of. There is another option that will work but only for apps that have limited number of users and limited number of post views. This option would be to store the user id within an array in each post object and everytime you want to display a post, you only need to check if that user id exist or not in that array.
But if a post can be viewd by millions of users, storing millions of ids within an array is not a good option because the problem in this case is that the documents have limits. So there are some limits when it comes to how much data you can put into a document. According to the official documentation regarding usage and limits:
As you can see, you are limited to 1 MiB total of data in a single document. So you cannot store pretty much everything in a document.