Query data relationship on Firebase Realtime Datab

2019-07-11 07:07发布

I need to query comments and request only user that listed in the comment by userId.

My database structure in Firebase realtime db:

{
  "comments" : {
    "c_id1" : {
      "commentId" : "c_id1",
      "commentText" : "text",
      "userId" : "u_id1"
    },
    "c_id2" : {
      "commentId" : "c_id2",
      "commentText" : "text",
      "userId" : "u_id3"
    },
  },

  "users" : {
    "u_id1" : {
      "userId" : "u_id1",
      "userName" : "name1",
    },
    "u_id1" : {
      "userId" : "u_id2",
      "userName" : "name2",
    },
    "u_id1" : {
      "userId" : "u_id3",
      "userName" : "name3",
    }
  }
}

What I need in the end is Comment[], where Comment is:

{
  "commentId" : "c_id",
  "commentText" :"text",
  "userId" : "u_id",
  "user" : {
    "userId":"u_id",
    "userName":"name"
  }
}

so, the class for Comment is

export class Comment {
  commentId: string;
  commentText: string;
  userId: string;
  user?: User;
}

So far I managed to get ALL users and then map them to comments on the client side. But wouldn't it be to much in case when db will have N number of users and only 2 comments, where N>>2?

  OnGetUsersForComments(){
    return this.angularFireDatabase.list("/comments").valueChanges()
      .subscribe((data) => {
        this.commentsUsers = data;
        this.OnGetCommentsForTask()
      });
  }

  OnGetCommentsForTask(){
    this.angularFireDatabase.list("/comments").valueChanges()
      .map((comments) => {
        return comments.map( (comment: TaskComment) => {
          this.commentsUsers.forEach((user: User) => {
            if (comment.userId === user.userId) {
              comment.commentUser = user;
            }
          });
          return comment;
        });
      })
      .subscribe((data)=> {
        this.comments = data;
      });
  }

Is there a way get only users from comments?

I also tried to add this to the User, but did not manage it to work:

"userComments" : {
  "uc_id1" : {
    "commentId" : c_id2
  },
}

Update 0

I have edited the question, I hope now is more clear.

I have been able to make it work like this: solution from - https://www.firebase.com/docs/web/guide/structuring-data.html and https://firebase.google.com/docs/database/web/read-and-write

 comments: TaskComment[] = [];

 onGetComments(){
    var ref = firebase.database().ref('/');

    ref.child('comments/').on('child_added', (snapshot)=>{
      let userId = snapshot.val().userId;
      ref.child('users/' + userId).on('value', (user)=>{
        this.comments.push( new TaskComment( snapshot.val(), user.val() ));
      });
    });
  }

but I want to convert this to Observable, because with this I can not see if the comment have been deleted without refreshing the page.


Update 1

With the help from comment bellow I came out with this implementation.

onGetComments(){
  this.angularFireDatabase.list("/comments").valueChanges()
    .mergeMap((comments) => {
      return comments.map((comment)=>{
        this.firebaseService
          .onListData('/users', ref => ref.orderByChild('userId').equalTo(comment.userId))
          .valueChanges()
          .subscribe((user: User[])=> {
            comment.user = user[0];
          })
        return comment;
      })
    })
    .subscribe((comment)=> {
      console.log(comment);
    });
}

This returns separate comments, where I would rather receive Comment[], I'll try to use child events: "child_added", "child_changed", "child_removed", and "child_moved" with snapshotChanges() instead .valueChanges().

1条回答
▲ chillily
2楼-- · 2019-07-11 07:33

Ok so according to your updates, I would personally first create a couple helper interfaces:

interface User {
    userId: string;
    userName: string;
}

interface FullComment {
    commentId: string;
    userId: string;
    user: User;
}

interface CommentObject {
    commentId: string;
    commentText: string;
    userId: string;
}

And then super handy helper methods:

getUser(uid: string): Observable<User> {
    return this.db.object<User>(`/users/${uid}`)
    .valueChanges()
}

getFullComment(commentObject: CommentObject): Observable<FullComment> {
    return this.getUser(commentObject.userId)
    .map((user: User) => {
        return {
            commentId: commentObject.commentId,
            commentText: commentObject.commentText,
            user: user,
        };
    });
}

So finally look how easy it becomes to get the FullComment objects observable:

getComments(): Observable<FullComment[]> {
    return this.db
    .list(`/comments`)
    .valueChanges()
    .switchMap((commentObjects: CommentObject[]) => {
        // The combineLatest will convert it into one Observable
        // that emits an array like: [ [fullComment1], [fullComment2] ]
        return Observable.combineLatest(commentObjects.map(this.getFullComment));
    });
}

I think this is what you need. Please let me know if this is helpful. Happy coding with observables ;)

Latest update: Previously forgot to make a last transformation to fix the TypeError, so now it must be ok.

查看更多
登录 后发表回答