简体   繁体   English

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

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

Here is how my database is structured: challenges table & users table这是我的数据库的结构:挑战表用户表

Here is the error I'm getting: error image这是我得到的错误:错误图片

I want to use the "created_by" field which is also a document id for the users table, where I want to retrieve both the display name and the photo URL.我想使用“created_by”字段,它也是用户表的文档 ID,我想在其中检索显示名称和照片 URL。

I'm not all the way sure how promises work and I have a feeling that is why I'm struggling, but the code I have thus far is below:我并不完全确定 Promise 是如何工作的,我有一种感觉,这就是我在挣扎的原因,但到目前为止我所拥有的代码如下:

Data Retrieval:数据检索:

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

Challenges DAO:挑战 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}
  }

Users DAO:用户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;
  }
}

You're getting close.你越来越近了。 All that's left to do is to call getUserData for each UID you get back from getChallenges .剩下要做的就是为从getChallenges返回的每个 UID 调用getUserData

Combining these two would look something like this:将这两者结合起来看起来像这样:

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

console.log(challenges.challengeName, users);

The new thing here is Promise.all() , which combines a number of asynchronous calls and returns a promise that completes when all of them complete.这里的新东西是Promise.all() ,它结合了许多异步调用并返回一个 promise ,当它们全部完成时完成。


Your code looks a bit odd to me at first, because of the way you return the data from getChallenges .你的代码起初对我来说有点奇怪,因为你从getChallenges返回数据的方式。 Instead of returning three arrays with simple values, I'd recommend returning a single array where each object has three values:我建议不要返回三个 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;
  }

If you then want to add the user name to each object in this array, in addition to the UID that's already there, you could do:如果您想将用户添加到此数组中的每个 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.

相关问题 如何使用另一个集合中的字段值更新Mongodb集合中的文档 - How to update document in Mongodb collection with a field value from another collection 如何在另一个集合中插入带有字段引用文档的文档 - How to inserting a document with field referencing document in another collection 如何从基于带有 firestore 的字段的集合中获取文档? - How to get document from a collection based on a field with firestore? 如何使用Meteor通过ID从另一个集合中的文档返回文档属性? - How do I return document property from document in another collection by ID using Meteor? 如何从 Firestore 集合中的文档中获取数据? - How do I get the data from a document in a collection in Firestore? 如何更新文档以在 mongoose 中嵌入来自不同集合的现有文档 - How to update a document to embed an existing document from a different collection in mongoose 在字段为 objectId 但引用另一个集合的集合中查找文档 - Finding a document in a collection whose field is an objectId but refers to another collection MongoDB:您能否将一个集合作为字段包含在另一个集合的文档中? - MongoDB: Can you include a collection as a field in a document of another collection? 如何对一个集合中多个文档的值求和并将总和推送到另一个集合中的文档 - How to sum the values from multiple documents in one collection and push total sum to document in another collection 如何使用文档ID从mongoDB集合中删除文档? - How to delete document from mongoDB collection using the document's ID?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM