I am trying to update a Firestore document by adding a new "Question Array" (containing the details of the question inside of the array).
I'd like to name of this new "field" inside the firestore document to follow a consistent naming convention whose value changes dynamicially with the number of question arrays in the document.
i.e. Adding adding the 5th question array in the document would take the current number of questions in the document (4) and add 1 to it (making 5). Then it would attach this value to the actual name of the new field being created (i.e. 'question/+(5)/ = [question details]. The code below might clarify what I'm trying to accomplish.
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...)
};
FOUND A SOLUTION:
So after further investigation, the only solution that I found for this problem is to adjust what is being called. rather than trying dynamically name the field, simply pass the "key" as the name of one of the objects within an object array (the object array is named "questions"). The array of objects, each index containing the object "state" which contains the question details.
This solution requires 2 updates to the document; 1 to add the new question object into the document, and another update to make changes to preexisting fields in the document.
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...)
};
``