如何使用一个集合中的文档字段来检索另一个集合中的另一个文档字段?

时间:2020-04-12 05:21:38

标签: javascript typescript firebase web google-cloud-firestore

这是我的数据库的结构: challenges tableusers table

这是我遇到的错误:error image

我想使用“ created_by”字段,该字段也是users表的文档ID,我想在其中检索显示名称和照片URL。

我不能一直确定promises如何工作,我有种感觉,这就是为什么我在努力,但是到目前为止,我的代码如下:

数据检索:

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;
  }
}

1 个答案:

答案 0 :(得分:0)

您正在接近。剩下要做的就是为从getUserData返回的每个UID调用getChallenges

将这两者结合起来看起来像这样:

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

console.log(challenges.challengeName, users);

这里的新事物是Promise.all(),它结合了许多异步调用,并返回一个在所有调用完成后都会完成的promise。


起初,您的代码对我来说有点奇怪,因为您从getChallenges返回数据的方式如此。建议不要返回一个带有简单值的三个数组,而是建议返回一个单个数组,其中每个对象都具有三个值:

  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;
  }

如果您想将用户 name 添加到该数组中的每个对象,除了已经存在的UID之外,还可以执行以下操作:

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

console.log(challenges);
相关问题