【问题标题】:I'm trying to save an array from subdocuments inside other subdocument but it does not我正在尝试从其他子文档中的子文档中保存一个数组,但它没有
【发布时间】:2021-09-30 12:06:36
【问题描述】:

我想保存这个,但猫鼬没有。这是 api、模型和控制台显示的内容。

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(`/`)
}

这是我的模型:

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
});

这就是控制台向我展示的内容

{
  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'
}

我已尝试多次解决此问题,但无法保存答案!我已经在 mongo 上查看了我的数据库,但它并没有出现在那里!!!!

【问题讨论】:

  • 所有.save() 都被注释掉了。您需要保存才能更新数据
  • 当我执行它时,它不会按我想要的方式保存
  • 您能否添加它正在保存的内容以及您想要的内容? @AlejandroJesúsArellano

标签: node.js arrays object mongoose subdocument


【解决方案1】:

为了便于阅读,我粘贴了您的代码 sn-p here

在第 42 行,您在 if 块结束后创建了一个块 ({}),没有任何 elseif 或任何东西,我不确定这是不是原因,但值得调查

在第 43 行,您正在修改 newExam.questions.answers,但在第 44 行,您将 newExam.answers 标记为已修改。我猜您将错误的子文档标记为已修改。尝试纠正并让我知道它是否已修复(或未修复!)。

【讨论】:

    猜你喜欢
    • 2015-05-16
    • 2015-10-31
    • 2020-09-17
    • 1970-01-01
    • 2013-09-20
    • 2020-07-18
    • 2016-10-16
    • 2017-06-13
    • 2018-04-12
    相关资源
    最近更新 更多