【问题标题】:Joining collection and sub-collection in firestore (web)在 firestore (web) 中加入集合和子集合
【发布时间】:2021-01-25 10:40:44
【问题描述】:

我正在尝试学习 Firestore,但在连接集合和子集合中的数据时遇到了一些问题。子集合的名称已知为players

-match_stats (collection)
  |_ document with random ID
    |_ map (field - string)
    |_ scorehome (field - Number)
    |_ scoreaway (field - Number)
      |_ Sub-collection (named: Players)
        |_ documents with random ids
          |_ Field (Player names, ex. Christopher)
            |_ playerkills
            |_ playerdeaths

我已经能够分别console.log每个集合,但我希望集合和子集合包含在同一个对象中,所以我可以合并数据。我也愿意接受有关如何解决此问题的其他建议。

firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();

export default {
  data() {
    return {

      matchInfo: [],

    };
  },
  methods: {
    readMatches() {
      this.matchInfo = [];
      db.collection("match_stats")
      .get()
      .then(matchQuerysnapshot => {
        matchQuerysnapshot.docs.forEach(doc => {
          console.table(doc.data());
          db.collection("match_stats").doc(doc.id).collection("players")
          .get()
          .then(playersQuerySnapshot => {
            playersQuerySnapshot.docs.forEach(doc => {
            console.table(doc.data());
            })
          })
        })
      })
    },
  },
  mounted() {
    this.readMatches();
  },
};

【问题讨论】:

    标签: javascript vue.js google-cloud-firestore


    【解决方案1】:

    您可以执行以下操作。首先,您获取所有父文档,同时使用 Promise.all() 并行查询所有 players 子集合。

        var db = firebase.firestore();
    
        var promises = []
        db.collection('match_stats').get()
            .then(snapshot => {
                snapshot.forEach(doc => {
                    ...
                    promises.push(doc.ref.collection('players').get());
                })
                return Promise.all(promises);
            })
            .then(results => {
                results.forEach(querySnapshot => {
                    querySnapshot.forEach(function (doc) {
                        console.log(doc.id, " => ", doc.data());
                    });
                });
            });
    

    注意results 数组的顺序与promises 数组的顺序完全相同。

    我的回答基于此 similar question 进行更改以适应您的问题。

    【讨论】:

      【解决方案2】:

      Fire 存储有自己的钩子,用于在页面加载时抓取数据。

      data() {
          return {
      
            matchInfo: [],
      
          };
        },
      firestore() {
            return {
              matchInfo: db.collection('players')
              ... The rest of your code ...        
      
            }
          },
      

      【讨论】:

        猜你喜欢
        • 2019-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-15
        • 1970-01-01
        • 2021-03-10
        • 2020-12-25
        • 2022-01-19
        相关资源
        最近更新 更多