在Firebase实时数据库中模拟更新数组和嵌套对象

时间:2020-06-18 09:26:21

标签: javascript firebase firebase-realtime-database

设置方法之后,我想调用update方法来更新实时数据库中的某些特定字段。

Database structure

上图演示了我的数据库结构,当第一个用户来到时,它是这样创建的。下面提到的代码:-

async function userJoinContest(userId) {
    var count = 1000;
    var playersJoined = 0;
    const joiningFlag = await checkUserJoinContest(userId);
    // console.log("************", joiningFlag);

    if (joiningFlag === true) {
        var docRef = ref.child(`joinedUsers/${currentDate}/${count}`)

        docRef.set({
                Quiz_Info: {
                    questionSet: questionSetUser,
                    answerSet: answerSetUser
                },
                players: [userId],
                userAnsSet: {
                    [userId]: userAnswerObj
                },
                totalPlayersJoined: playersJoined + 1
            })
            .then(() => {
                console.log("Successfully saved")
            })
            .catch(error => {
                console.log(error);
            })
    } else {
        console.log("user cannot join the contest. You dont have enough balance to join the contest");
        return false;
    }
}

现在我的问题是:- 对于第一个用户,我调用set方法,现在从第二个用户起,我要调用更新方法。

当第二个用户进入或加入时,我只想更新某些特定字段,即仅应更新“玩家”,“ totalPlayersJoined”和“ userAnsSet”字段。因此,在“玩家”(它是一个数组)中,添加了第二个用户ID,依此类推,“ totalPlayersJoined”被增加了1,依此类推,即它将变为2,并且userAnsSet也得到了类似的更新,如上图所示。 / p>

谢谢

0 个答案:

没有答案