我从一个集合中获取一组文档ID,以用于查询另一个集合。这是我的查询的样子:
firebase
.firestore()
.collection("users")
.doc(this.props.userID)
.get()
.then((snapshot) => {
const postIDs = snapshot.data().posts;
firebase
.firestore()
.collection("posts")
.where(firebase.firestore.FieldPath.documentId(), "in", postIDs)
.orderBy("timestamp")
.get()
.then((snapshot) => {
console.log(snapshot.data());
});
});
这snapshot.data()
是不确定的,因此我假设查询有问题。我可以确认中存在有效的ID postIDs
。
数据库的结构如下:
users:
-- user with userID
---- displayName
---- etc.
---- posts (array of postIDs)
posts:
-- post with postID
当您调用时collection().get()
,响应不保留data()
或id
属性,因为它返回了多个文档(理论上无论如何),因此docs
,即使只有一个与查询匹配的文档,您也只能通过该属性访问这些文档。
因此,如果要访问与查询匹配的文档,请执行以下操作:
firebase.firestore()
.collection("posts")
.where(firebase.firestore.FieldPath.documentId(), "in", postIDs)
.orderBy("timestamp")
.get()
.then((snapshot) => {
const posts = snapshot.docs.map(doc => doc.data());
console.log(posts);
...
}
您只能致电,snapshot.data()
或者snapshot.exists
如果您在查询中指定了一个文档,则firestore().collection("posts").doc(someDocID).get()
就像在第一个查询中一样。如果不是,请参考snapshot.docs
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句