firebase - 如何组合两个 Redux Firebase Cloud Firestore 查询?

标签 firebase react-native redux google-cloud-firestore expo

我有两个 redux 查询从我的 Firebase Firestore 中提取帖子。第一个成功显示了我关注的人的所有帖子:

export function fetchUsersFollowingPosts(uid) {
    return ((dispatch, getState) => {
        firebase.firestore()
            .collection("posts")
            .doc(uid)
            .collection("userPosts")
            .orderBy("creation", "asc")
            .get()
            .then((snapshot) => {
                const uid = snapshot.query.EP.path.segments[1];
                const user = getState().usersState.users.find(el => el.uid === uid);


                let posts = snapshot.docs.map(doc => {
                    const data = doc.data();
                    const id = doc.id;
                    return { id, ...data, user }
                })

                for (let i = 0; i < posts.length; i++) {
                    dispatch(fetchUsersFollowingLikes(uid, posts[i].id))
                }
                dispatch({ type: USERS_POSTS_STATE_CHANGE, posts, uid })

            })
    })
}
第二个显示了我自己的所有帖子。
export function fetchUserPosts() {
    return ((dispatch) => {
        firebase.firestore()
            .collection("posts")
            .doc(firebase.auth().currentUser.uid)
            .collection("userPosts")
            .orderBy("creation", "desc")
            .get()
            .then((snapshot) => {
                let posts = snapshot.docs.map(doc => {
                    const data = doc.data();
                    const id = doc.id;
                    return { id, ...data }
                })
                dispatch({ type: USER_POSTS_STATE_CHANGE, posts })
            })
    })
}
这是我目前从我关注的人中列出用户的地方。但是我如何将它们组合起来,以便我可以在一个 FlatList 中显示我的帖子和我关注的人的帖子?
function Feed(props) {
    useStatusBar('dark-content');
    const [posts, setPosts] = useState([]);
    const [refreshing, setRefreshing] = useState(false)

    useEffect(() => {
        if (props.usersFollowingLoaded == props.following.length && props.following.length !== 0) {
            props.feed.sort(function (x, y) {
                return y.creation.toDate() - x.creation.toDate();
            })

            setPosts(props.feed);
            setRefreshing(false)
        }

    }, [props.usersFollowingLoaded, props.feed])

    
    return (
        <View style={styles.background}>
             {posts.length > 0 ?
            <View style={styles.containerGallery}>
                <FlatList
                    refreshControl={
                        <RefreshControl
                            refreshing={refreshing}
                            tintColor="white"
                            onRefresh={() => {
                                setRefreshing(true);
                                props.reload()
                            }}
                        />
                    }
                    showsVerticalScrollIndicator={false}
                    numColumns={1}
                    horizontal={false}
                    data={posts}
                    renderItem={({ item }) => (
                        <View style={styles.containerImage}>
                            <Card title={item.title} onPress={() => props.navigation.navigate(routes.GOOD_STUFF_DETAIL, { item: item, postId: item.id, uid: item.user.uid, user: item.user,})} showLike={true} author={"Recommended by " + item.user.name} likeItem={item} likeCount={item.likesCount} icon={categories.categories[item.categoryID].icon} timeStamp={timeDifference(new Date(), item.creation.toDate())}/>
                        </View>
                    )}
                />
                
            </View>
            : <NothingHere title="Follow friends" text="To see their Good Stuff here" icon="search" color="white"/> }
        </View>

    )
}
const mapStateToProps = (store) => ({
    currentUser: store.userState.currentUser,
    following: store.userState.following,
    feed: store.usersState.feed,
    usersFollowingLoaded: store.usersState.usersFollowingLoaded,
})

const mapDispatchProps = (dispatch) => bindActionCreators({ reload }, dispatch);

export default connect(mapStateToProps, mapDispatchProps)(Feed);
下面是我的数据结构:
Firestore data structure 1
Firestore data structure 2
Firestore likes substructure
谢谢阅读!

最佳答案

也许我误解了数据库结构,但 AFAIK 似乎不可能将两个查询结合起来。从我所看到的数据库结构来看,您想要检索您(用户 A)给“赞”的用户 B 的帖子。为了获得该信息,您扫描路径 posts/{userUID}/userPosts/{docId}/likes .鉴于查询扫描不同的集合范围,我看不到混合它们的方法。
另外,为了论证的目的,让我们假设您已经有一个包含您关注的人的用户 UID 的列表。然后,更接近所需行为的 Firestore 查询功能是 Collection Group queries .记住数据库的结构:

posts
  uid1
    userPosts
      doc1
      doc2
  uid2
    userPosts
      docX
      docY
本质上,集合组查询是一种同时查询所有 userPosts 的方法。立即收藏。如果每个文档都将作者 ID 作为一个字段,您将能够执行以下操作:
db.collectionGroup("userPosts").where("uid", "in", ListOfFollowedUsers)
这不会完全解决问题,因为 in operator 子句限制为 10 个值,因此您最多可以为 10 个关注用户应用它。
总的来说,我建议将查询分开并将它们合并到应用程序代码中。

关于firebase - 如何组合两个 Redux Firebase Cloud Firestore 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65870917/

相关文章:

javascript - 如何将用户的 displayName 添加到 Firestore 数据库集合条目?

android - uri 图像未在 React native ImageView 中呈现

javascript - 在 Context 消费者上使用 useContext() 时,React Context "Property ' 状态'不存在

reactjs - React Redux 连接 API 不注入(inject)调度属性

javascript - Ngrx 所有重新选择选择器在单状态切片更改时运行

javascript - 遍历嵌套的 firebase 对象 - Javascript

javascript - 云函数 onUpdate 不起作用

javascript - 将回调与 Action 创建者一起使用

javascript - 只听特定范围内按键的 child 的变化?

reactjs - react native 平面列表逆序