I'm trying to save an array from subdocuments inside other subdocument but it does not

Viewed 31

Im trying to save this, but mongoose does not. This is the api, model and what the console show me.

newExam = async (req, res)=>{
    hasItUsernameTwo(req,res)
    const user = await User.findById(req.user),
    examData = JSON.parse(req.body.deepFormJSON),
    newExam = new Exam();
    console.log(examData)
    console.log(examData)
    newExam.title = examData.title
    newExam.description = examData.description
    newExam.author = user.username
    newExam.questions = []
    // para crear el array de objetos con preguntas
    if(Array.isArray(examData.questions.question)){
        examData.questions.question.forEach(e => {
            newExam.questions.push({
                question: e,
            })
        })
        for (var i = 0; i < examData.questions.question; i++) {
            newExam.questions[i].answers = []
        }
    } {
        newExam.questions.push({
            question: examData.questions.question
        })
        newExam.questions.answers = []
    }
    // para crear el array con las respuestas de cada pregunta
    // const get = examData.questions.answers.answer.forEach(async (e, i, array) => {
    //     if(Array.isArray(examData.questions.question)){
    //         newExam.questions[i].answers.push({answer: e})
    //     } {
    //         newExam.questions.answers.push({answer: e})
    //     }
    //     // return newExam.save()
    // });
    // await Promise.all(get)
    for (const [i, e] of examData.questions.answers.answer.entries()){
        if(Array.isArray(examData.questions.question)){
            newExam.questions[i].answers.push({answer: e})
            newExam.questions[i].markModified("answers")
        } {
            newExam.questions.answers.push({answer: e})
            newExam.markModified("answers")
        }
    }
    // for (const [i, e] of examData.questions.answers.correct.entries()){
    //     if(Array.isArray(examData.questions.question)){
    //         for(const [index, element] of newExam.questions[i].answers.entries()){

    //         }
    //     } {
    //         for(const [index, element] of newExam.questions.answers.entries()){

    //         }
    //     }

    // }
    console.log(newExam.questions.answers)
    // para crear el array con los valores buleanos de cada pregunta
    // await newExam.save();
    // await newExam.validate();
    // user.exams.push(newExam._id)
    // await user.save()
    console.log(newExam)
    // res.redirect(`exams/${newExam._id}`)
    res.redirect(`/`)
}

This is my model:

answerSchema = new Schema({
    answer: String,
    correct: String
}),

questionsSchema = new Schema({
    question: {
        type: String,
        required: "The questions are required"
    },
    answers: [answerSchema]
}),

examSchema = new Schema({
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    }, 
    author: { 
        type: String, 
        ref: "User",
        required: `The author is required.`
    },
    questions: [questionsSchema],
    usersDone: [{
        type: Schema.ObjectId, 
        ref: "User",
    }]
}, {
    timestamps: true,
    versionKey: false
});

And this is what the console show me

{
  title: 'JavaScript',
  description: 'An Exam For JavaScript Users',
  questions: { question: 'What is JavaScript?', answers: { answer: [Array] } }
}
[
  { answer: 'An extension for Java' },
  { answer: 'A programming language' },
  { answer: 'Idk, but it has 14 million of users' },
  { answer: 'The Snake Game' }
]
{
  usersDone: [],
  _id: 60fa9b14ac5f133b70fa2ded,
  questions: [
    {
      _id: 60fa9b14ac5f133b70fa2dee,
      question: 'What is JavaScript?',
      answers: []
    }
  ],
  title: 'JavaScript',
  description: 'An Exam For JavaScript Users',
  author: 'AlejandroArellano'
}

I have tried to solve this a multiple times but it does not save the answers! I have checked out on my database on mongo, and it does not appaer there!!!!

1 Answers

I pasted your code snippet here for readability.

In line 42,you made a block ({}) after the end of if block, without any else or if or anything, I am not sure it's the cause but worth looking into it

In line 43, you are modifying newExam.questions.answers but in line 44, you are marking newExam.answers as modified. I guess you are marking the wrong sub-document as modified. Try to rectify and let me know if it is fixed (or not!).

Related