0

我正在尝试通过添加一个新的“问题数组”(包含数组内部问题的详细信息)来更新 Firestore 文档。

我想在 firestore 文档中命名这个新的“字段”,以遵循一致的命名约定,其值会随着文档中问题数组的数量而动态变化。

即在文档中添加第 5 个问题数组将采用文档中的当前问题数 (4) 并将其添加 1(使 5)。然后它会将此值附加到正在创建的新字段的实际名称(即'question/+(5)/ = [question details]。下面的代码可能会阐明我要完成的工作。

export const createFlashcardQuestion = (state) => {

    return (dispatch, getState, { getFirebase, getFirestore}) => {

         (...)
    
        const numberOfQuestions = state.numberOfQuestions;    <--- THIS IS THE VALUE I WANT TO REPLACE THE # with

        # = numberOfQuestions;                                <----- Placed here for clarity that this is the value trying to be ammended to the question array name.

        firestore.collection(...PATH BLAH BLAH...).update({   <----- I SIMPLIFIED THE PATH JUST FOR THIS QUESTION
            numberOfQuestions: numberOfQuestions,             <---- THIS IS THE NEW # OF QUESTIONS
            lectureUpdatedAt: new Date(),
            question#: [state],                               <-------- THIS IS THE LINE I AM STRUGGLING. I want the "#" to somehow equal the interger value found in "numberOfQuestions".
            

        }).then(() => {

            (...Dispatch and Thunk Mumbo Jumbo...)

    
};
4

1 回答 1

0

找到解决方案:

因此,经过进一步调查,我发现此问题的唯一解决方案是调整所调用的内容。而不是尝试动态命名字段,只需将“键”作为对象数组中的一个对象的名称传递(对象数组名为“问题”)。对象数组,每个索引包含包含问题详细信息的对象“状态”。

此解决方案需要对文档进行 2 次更新;1 将新问题对象添加到文档中,并进行另一个更新以更改文档中预先存在的字段。

export const createFlashcardQuestion = (state) => {

    return (dispatch, getState, { getFirebase, getFirestore}) => {

         (...)
    

        const key = state.numberOfQuestions;

        var newQuestion = {};
        newQuestion[`questions.${key}`] = {
            state
        };

        firestore.collection(...PATH BLAH BLAH...).update(
            newQuestion)

        firestore.collection(...PATH BLAH BLAH...).update({
            numberOfQuestions: numberOfQuestions,
            lectureUpdatedAt: new Date(),
            

        }).then(() => {

            (...Dispatch and Thunk Mumbo Jumbo...)

    
};
`` 
于 2020-08-01T22:25:10.340 回答