MongoDB: 如何插入复杂模式

MongoDB: How to insert complex schema

我正在构建一个 "Test" 系统。每个测试都有一些问题。 每个问题都有答案。

我正在 JSON 从另一个服务器创建问题:

{
     requestType: 'CreateNewQuestion',
     questionId: 17447,
     subject: "Math",
     subsubject: "Heshbon",
     questionText: "1+4 Equels?",
     answers: [{text : "2",rightAnswer : false},
               {text : "35",rightAnswer : false},
               {text : "5",rightAnswer : true},
               {text : "9",rightAnswer : false}]
}

我构建了 2 个模式:

module.exports = mongoose.model('Answer' ,
{
    text: String,
    rightAnswer: Boolean
}

);

module.exports = mongoose.model('Question' ,
{
    questionId: Number,
    subject: String,
    subsubject: String,
    questionText: String,
    answerTimeAvg: Number,
    fastestAnswer: Number,
    answers: [{ type : mongoose.Types.ObjectId, ref: 'Answer' }]
}
);

我创建了一个获取 JSON 的函数并尝试将其保存为:

var QuestionSchema = require('./schemas/question');
var AnswerSchema = require('./schemas/answer');

CreateNewQuestion: function (message) {

    var information = {
        questionId: message.questionId,
        subject: message.subject,
        subsubject: message.subsubject,
    }

    //Save Question
    var record = new QuestionSchema(information);
    record.save(function (err) {});
}

如何创建答案对象并将其填充到问题中?

我尝试了一些方法但总是出错,

正确的方法是什么?

我试图阅读 "mongoosejs.com/docs" 但网站已关闭 :(

我需要将模型更改为:

module.exports = mongoose.model('Question' ,
{
    subject: String,
    subsubject: String,
    questionText: String,
    answerTimeAvg: Number,
    fastestAnswer: Number,
    answers: [{ type : mongoose.Schema.Types.ObjectId, ref: 'Answer' }]
} );

并先保存答案,然后再使用 ID:

CreateNewQuestion: function (message) {

    ////////////////////////
    // Saving the answers //
    ////////////////////////

    var answers = message.answers;
    var answers_ids = [];

    for(var i in answers) {
        var answer = new AnswerSchema(answers[i]);
        answer.save();
        answers_ids.push(answer._id);
    }


    /////////////////////////
    // Saving the question //
    /////////////////////////

    var information = {
        subject: message.subject,
        subsubject: message.subsubject,
        questionText: message.questionText,
        answerTimeAvg: 0,
        fastestAnswer: 0,
        answers: answers_ids
    }

    var record = new QuestionSchema(information);
    record.save(function (err) {
        if (err) {
            console.log("Bad = " + err);
            var result = "bad";
            message.sendReplay({result: result});
        }
        else {
            var result = "AllGood";
            message.sendReplay({result: result});
        }
    });

},