簡體   English   中英

如何使用一個集合中的文檔字段從不同集合中檢索另一個文檔字段?

[英]How do I use a document's field from one collection to retrieve another document field from a different collection?

這是我的數據庫的結構:挑戰表用戶表

這是我得到的錯誤:錯誤圖片

我想使用“created_by”字段,它也是用戶表的文檔 ID,我想在其中檢索顯示名稱和照片 URL。

我並不完全確定 Promise 是如何工作的,我有一種感覺,這就是我在掙扎的原因,但到目前為止我所擁有的代碼如下:

數據檢索:

UsersDao.getUserData(ChallengesDao.getChallenges().then(result => {return result['author'][0]})).then(result => {console.log(result)})

挑戰 DAO:

export default class ChallengesDao {

  static async getChallenges() {
const db = require('firebase').firestore();
    // const challenges = db.collection('challenges').limit(number_of_challenges)
    // challenges.get().then(())

    const snapshot = await db.collection('challenges').get()

    const names = snapshot.docs.map(doc => doc.data().name)
    const createdBy = snapshot.docs.map(doc => doc.data().created_by)
    const highScores = snapshot.docs.map(doc => doc.data().high_score.score)
    return {challengeName: names, author: createdBy, score: highScores}
  }

用戶DAO:

const db = require('firebase').firestore();

export default class UsersDao {
  static async getUserData(uid: string) {
    let userData = {};
    try {
      const doc = await db
        .collection('users')
        .doc(uid)
        .get();
      if (doc.exists) {
        userData = doc.data();
      } else {
        console.log('User document not found!');
      }
    } catch (err) {}
    return userData;
  }
}

你越來越近了。 剩下要做的就是為從getChallenges返回的每個 UID 調用getUserData

將這兩者結合起來看起來像這樣:

let challenges = await getChallenges();
let users = await Promise.all(challenges.author.map((uid) => getUserData(uid));

console.log(challenges.challengeName, users);

這里的新東西是Promise.all() ,它結合了許多異步調用並返回一個 promise ,當它們全部完成時完成。


你的代碼起初對我來說有點奇怪,因為你從getChallenges返回數據的方式。 我建議不要返回三個 arrays 的簡單值,而是返回一個數組,其中每個 object 具有三個值:

  static async getChallenges() {
    const db = require('firebase').firestore();
    const snapshot = await db.collection('challenges').get();

    const challenges = snapshot.docs.map(doc => { name: doc.data().name, author: doc.data().created_by, score: doc.data().high_score.score });

    return challenges;
  }

如果您想將用戶添加到此數組中的每個 object 中,除了已經存在的 UID 之外,您可以執行以下操作:

let challenges = await getChallenges();
await Promise.all(challenges.forEach(async(challenge) => {
  challenge.user = await getUserData(challenge.author);
});

console.log(challenges);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM