firebase - 如何在 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);
});
});
解决方案
您需要使用代码中的 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
推荐阅读
- delphi - 如何为任何键盘检测 3 个按键与 Firemonkey 中的 Shift 相结合?
- node.js - 对话流中有没有办法在重新加载网页后保留会话的聊天记录?
- javascript - DOCX Javascript 库附加表行
- c++ - 网络宠物 switch 语句,添加到一个 int 不知道为什么 c++
- java - JComponent 对象是否在运行时被 JVM 序列化/反序列化?
- function - 创建没有输入的算术函数
- python - 用字典的值替换数据框的索引值?
- javascript - 在 NodeJS 中处理 post 请求失败的正确方法是什么?
- javascript - 为什么 app.use(fn, '/api/auth', require('./routes/auth.routes')) 错误?
- java - 如何以编程方式设置 RelativeLayout 的 layout_constraintTop_toBottomOf “父级”?(安卓)