MongoDB:如何插入复杂的模式

时间:2015-01-14 16:54:13

标签: json node.js mongodb express mongoose

我正在建立一个“测试”系统。每个测试都有一些问题。 每个问题都有答案。

我正在使用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) {});
}

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

我尝试了几件事,但不断收到错误,

什么是正确的方法?

我试图阅读“mongoosejs.com/docs”,但该网站已关闭:(

1 个答案:

答案 0 :(得分:0)

我需要将模型更改为:

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

},