【问题标题】:Query two collections with a related field and same value in firebase在firebase中查询具有相关字段和相同值的两个集合
【发布时间】:2021-07-10 14:31:08
【问题描述】:

所以基本上我试图实现的是获取每个查询的事件的参与者文档。请查看发布的图像。两者都有一个需要匹配的公共 EventId 字段。下面的代码仅适用于第一次迭代,但立即停止在 getRealtimeChild() 之前。Events 文档有一个 Id 字段

    useEffect(() => {

    //Fetch events ordered by timestamp
    const eventsRef = realDB.ref('Events').orderByChild('EventTimestamp').limitToFirst(3);

    setLoader(true);

    eventsRef.on('value', (snapshot) => {
        //var o = 0;
        //var i = 0;
    //Fetch Participants of each events
        snapshot.forEach(function (events) {
            // console.log(events.key)
            // console.log('outer =>'  ,o+=1)

            getRealtimeChild('Participants', 'EventId', events.key).limitToLast(5).get().then(function (snapshot) {
                console.log(events.key)
                snapshot.forEach(function (p) {
                    // console.log('p =>',p.key)
                    // console.log('inner =>'  ,i+=1)

                    participants=[];
                    participants.push(p.val())
                    setParticipantList([])
                    setParticipantList(participants)
                    // console.log(participants)
                    // console.log(participantList)
                })
                eventList.push(Object.assign(events.val(),{id: events.key},{participants:participantList}));

                // console.log(participantList)


            });

        });

        setEventsList(eventList)
        setLoader(false);
        console.log(eventList)


    });

}, [])

【问题讨论】:

    标签: javascript reactjs firebase firebase-realtime-database


    【解决方案1】:

    您可以使用equalTo 方法获取特定活动的参与者。

    const ref = realDB.ref('Events/Participants')
    const snapshot = await ref.orderByChild('EventId').equalTo('<EVENT-ID>').once("value")
    console.log(snapshot.val());
    

    您还可以根据需要使用limitToFirstlimitToLast 方法。

    method description
    limitToFirst Sets the maximum number of items to return from the beginning of the ordered list of results.
    limitToLast Sets the maximum number of items to return from the end of the ordered list of results.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-07
      • 2022-12-05
      • 2013-12-23
      • 1970-01-01
      • 1970-01-01
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多