首页 > 解决方案 > 如何在 Firestore 中获取嵌套的参考数据?

问题描述

我正在尝试按日期获取数据并在 Firestore 中呈现 html,但我不能那样做。

顺序是错误的。因为,数据是按用户排序的。如何按日期获取数据?

{
  comments: {
    comment_1: {
     userRef: users/user_1,
     body: "body",
     createdAt: Timestamp,
    },
    comment_2: {
      userRef: users/user_2,
      body: "body",
      createdAt: Timestamp,
    },
    comment_3: {
      userRef: users/user_1,
      body: "body",
      createdAt: Timestamp,
    },
  },
  users: {
    user_1 : {
     name: "test"
    },
    user_2 : {
     name: "test"
    },
  }
}


db.collection('comments').orderBy('createdAt').get().then(snapshot=> {
    const comment = snapshot.data();
    comment.userRef.get().then(userSnapshot => {
      const userData = userSnapshot.data();
      const comment = document.getElementById('js-comment');
      const element = document.createElement('div')
      element.innerHTML = `<p>${comment.body}</p>`
      comment.appendChild(element);
    });
});

标签: firebasegoogle-cloud-firestore

解决方案


您需要使用代码中的 orderBy 日期字段对数据进行排序,但是,您提供的数据模型中没有 createdAt 字段。

如果您的评论数据如下所示

comments: {
    comment_1: {
     userRef: users/user_1,
     body: "body",
     createdAt: Timestamp
    },
    comment_2: {
      userRef: users/user_2,
      body: "body",
      createdAt: Timestamp
    },
    comment_3: {
      userRef: users/user_1,
      body: "body",
      createdAt: Timestamp
    },

时间戳字段可以通过在创建数据时让 firestore 使用 Timestamp.now() 填充字段来填充。

使用 orderBy 读取数据后的注释。如果您希望数据是递增顺序,则需要指定 ASCENDING,然后可以查找用户并且数据应该以正确的顺序显示。

此处对此进行了更多讨论https://firebase.google.com/docs/firestore/query-data/order-limit-data


推荐阅读