简体   繁体   English

Firebase Cloud Firestore noSQL

[英]Firebase Cloud Firestore noSQL

The database has a collection of users, questions and answers. 该数据库具有用户,问题和答案的集合。 see below 见下文

Users
------
firstName
lastName

Questions
-------
date
question

Answers
-------
date
answer
questionId
userId

Use case: get a users answers and the question to those answers. 用例:获取用户答案和这些答案的问题。 Display the question and answer 显示问题和答案

my code: 我的代码:

    //User Questions with Answers
this.db.collection('Answers', ref => ref.where('userId', '==', userId) ).snapshotChanges()
  .subscribe(data => {
    return data.map(a => {
      const data = a.payload.doc.data();
      console.log(data);
      console.log(data.questionId);
      //qa.answers.push(data);

      //Get each question from the answer now
      // bummer that this is a seperate request, very chatty
      var question = this.db.collection('Questions')
        .doc(data.questionId).valueChanges()
          .subscribe(ref => {

            console.log(ref);
            return ref;
          });   

      return {data, question};
    });
  });

2 questions: 2个问题:

  1. Is this the best way? 这是最好的方法吗? It makes a call to the server to get the question for every answer. 它调用服务器以获取每个答案的问题。 Seems chatty. 看起来很健谈。
  2. It does manage to get the data, although chatty, now how do I display it? 尽管确实很健谈,但它确实设法获取了数据,现在如何显示它?

Thanks, I'm new to noSQL and Firebase. 谢谢,我是noSQL和Firebase的新手。

2 - how display? 2-如何显示? "display it" where? “显示它”在哪里? In frontend~? 在前端〜?

If using AngularFire, you can try: 如果使用AngularFire,则可以尝试:

in .ts 在.ts中

answersCol : AngularFirestoreCollection<Answers>;
answersObersArray: Observable<Answers[]>;
answersArray: Array<Answers>;

this.answersCol  = this.db.collection('survey/' + userId);
this.answersObersArray = this.answersCol .valueChanges();

this.answersObersArray .subscribe(answers => {
   this.answersArray = answers ;//--Working with arrays
});

in .html 在.html中

<table class="table table-bordered">
  <tbody *ngFor="let answer of answersArray ">
         <tr style="font-weight:bold">
           <td>{{ answer  }}</td>
          </tr>
  </tbody>
</table>

(tested) (已测试)

If using Observable, you can try: 如果使用Observable,可以尝试:

in .ts 在.ts中

var answersCol = this.db.collection('answers/' + userId');//Check ur struct
answersObservArray: Observable<Answers[]>; //If you have a Answers class

this.answersObservArray= this.answersCol.valueChanges();

in .html 在.html中

<h4 class="title"> {{ (answersObservArray| async)}}</h4>

(no full tested) (未经过全面测试)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM