【问题标题】:Get field from subcollection's parent document从子集合的父文档中获取字段
【发布时间】:2020-05-18 18:22:15
【问题描述】:

我正在使用 Firestore 创建消息应用程序

目前我创建了一个函数,当用户在messageRoom 中写入消息时会触发该函数。每个messageRoom 文档都有一个名为messages 的子集合,其中包含房间的消息。 messageRoom 文档本身包含与 messageRoom 本身相关的数据,例如属于messageRoom 的用户。 messageRoom 包含一个名为 members 的字段,其中包含有关属于 messageRoom 的用户的信息

我想访问messageRoom 文档中的数据,而不是messages 子集合。目前以下代码不起作用。一个错误告诉我 members 字段未定义。我做错了什么?

exports.sendNotification = functions
  .firestore
  .document('messageRooms/{messageRoomId}/messages/{messageId}')
  .onCreate(  
  async (snapshot) => {
    /*
    Does something with the documents in the subcollection
    */

    //Get the DocumentReference of the parent doc
    const parentDocId = snapshot.ref.parent.id;

    admin.firestore().collection('messageRooms').doc(parentDocId).get('members').get().then(doc => {
      if (doc.exists) {
         console.log("Document data:", doc.data());
      } else {
          // doc.data() will be undefined in this case
          console.log("No such document!");
      }
      return; //return added to prevent crash
   }).catch(error => {
      console.log("Error getting document:", error);
   });
  }
);

【问题讨论】:

标签: node.js google-cloud-firestore google-cloud-functions


【解决方案1】:

我认为问题就在这里:

//Get the DocumentReference of the parent doc
    const parentDocId = snapshot.ref.parent.id;

快照是DocumentSnapshot,所以参考属性给我们DocumentReference。文档引用的属性parentCollectionReference (Google Doc)。因此,您必须找到的不是父母,而是“祖父母” :) 我可以说。也许试试:

const parentDocId = snapshot.ref.parent.parent.id;

但是,我不会在这里使用 .id 属性来获取下一行 .doc 的引用。 parent 属性已提供参考 (doc)。我不认为get 中的论点会改变任何东西,所以我会使用.data().messages 进入现场。最后我会使用:

const parentDocRef = snapshot.ref.parent.parent;

    parentDocRef.get().then(doc => { console.log(doc.data().members)})

希望对你有帮助!

【讨论】:

  • 当我尝试你的最后一个建议时,我得到 2 个错误:预期的 catch() 或 return 每个 then() 都应该返回一个值或抛出我以前遇到过但从未真正理解它
  • 这一定是环境问题,我在linux和node v10.14上没有这样的错误
猜你喜欢
  • 2023-04-02
  • 1970-01-01
  • 2019-10-06
  • 1970-01-01
  • 1970-01-01
  • 2022-07-08
  • 2022-11-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多