0

I made an app in that user can bookmark a page for that I create a collection in firestore

UserList(collection)
  -> UserIdgenerated(document)
     -> profile(sub-collection)
     -> fav(sub-collection)
        -> service_page (document)
           -> details

and I got another(say second collection) collection

service(collection)
 -> service_page(document)
   -> details

now I want to bookmark second collection document and display bookmarks in fragments. MY solution is to copy service_page details to userList fav collection

Question Is there any way to create bookmark by creating second collection document link to fav collection?

Code Scan
  • 42
  • 8
  • You can add the user UID as a field in service_page document so you know which user is the owner of that. – Dharmaraj Jun 23 '21 at 14:30
  • 1
    We are usually structuring a Firestore database according to the queries that we want to perform. What wrong with this schema? Besides that, having the same document in two places is not a bad approach. This technique [is called denormalization and is quite common when it comes to Firebase](https://stackoverflow.com/questions/54258303/what-is-denormalization-in-firebase-cloud-firestore/). – Alex Mamo Jun 23 '21 at 14:36
  • @dharmaraj, This Idea is not good because, suppose there is 100 or more service pages and a user bookmark 80 of them, then firestore has to go through all 100 service page to check that whether this User exist in that service page or not. It will be a time taking process and will create a big lag in the app. – Code Scan Jun 24 '21 at 02:24

1 Answers1

0

You can store a reference to that collection directly into Firestore, and then call .get() to retrieve the document when needed. In the following example, I'll push the reference into an array, you can use maps to include the reference with any additional data you may have.

val userID = Firebase.auth.currentUser.uid
db.collection("UserList/$userID/fav")
  .document("service_page")
  .update("Bookmarks", FieldValue.arrayUnion(db.doc("service/service_page"))
  .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully written!") }
  .addOnFailureListener { e -> Log.w(TAG, "Error writing document", e) }
Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
DIGI Byte
  • 4,225
  • 1
  • 12
  • 20