【发布时间】:2018-09-04 02:56:18
【问题描述】:
我需要什么:
我想在 Firestore 中保存文章或笔记及其各自的字段:
- 标题
- 内容(文本或段落)
- 创建日期
- 所有者(与其他人分享该文章 以及可以编辑它们的人:https://firebase.google.com/docs/firestore/solutions/role-based-access)
但是当我显示文章列表时,我不需要“内容”字段(以节省带宽)。我已经读过(也许我错了),无法使用 Firestore 进行查询以仅从文档中获取特定字段。
如果是普通的 SQL 从文章中获取特定的列(没有它的内容)它会是这样的:
SELECT title, creation_date, ...
FROM table_name;
所以我选择将两个根级集合的内容分开(为了灵活性和可扩展性)
我目前的结构:
文章收藏:
- `articles` [collection]
- `ARTICLE_ID` [document]
- `creatorId` [field]
- `title` [field]
- `date` [field]
- `owners` [obj field]
- {user1_id}: true
- {user2_id}: true
...
内容集合:
- `contents` [collection]
- `{ARTICLE_ID}` [document]
- `content` [field]
实时获取文章列表:
firebase.firestore().collection('articles')
.where(`owners.${user.uid}`, '==', true)
.onSnapshot(querySnapshot => {
const articles = []
querySnapshot.forEach((doc) => {
articles.push({
id: doc.id,
...doc.data()
})
})
// do something with articles array
})
在另一个视图中显示并获取整篇文章及其内容:
const db = firebase.firestore()
const articleRef = db.collection('articles').doc(articleId)
const contentRef = db.collection('contents').doc(articleId) // same Id as article
articleRef.get().then(articleDoc => {
if (articleDoc.exists) {
contentRef.get().then(contentDoc => {
if (contentDoc.exists) {
const article = {
...articleDoc.data(),
...contentDoc.data()
}
// full article obj
}
})
}
})
我的问题
您认为最好同时执行两个查询(getArticle 和 getContent)并使用 Promise.all() 等待而不是像我一样嵌套查询?
有没有更好的方法来通过一次查询或更有效地获取文章及其内容?一些提示或想法?
非常感谢您!
【问题讨论】:
-
你当前的代码有什么问题?
-
@FrankvanPuffelen 我改进了解释。代码正常工作。我对做好事只有存在主义的怀疑。
-
喜欢评论“存在的怀疑”精彩
标签: javascript firebase google-cloud-firestore