猫鼬:将数据插入子数组

时间:2018-08-19 19:23:09

标签: javascript mongodb mongoose

我正在尝试用猫鼬创建子数组,并且很难插入子文档。 我的架构是这样的:

     var SurveySchema = mongoose.Schema({
      question_id: { type: String, unique: true },
      question_text: { type: String, required: true }, 
      //answer's object. will contain 4 answers
      answers: { type:
        [{
          answer_id: { type: String, unique: true },
          answer_text: { type: String, required: true }, 
          next_question: { type: String, required: true },
          platforms: {
            type: [{
              platform_id: { type: String, required: true },
              platform_name: { type: String, required: true },
              platform_weight: { type: Number, required: true },
            }]
          }
        }]
      }
    });
var SurveySchemaExport = module.exports = mongoose.model('Survey', SurveySchema);

我要插入数据库的数据如下所示:

{
    "question_id": "1",
    "question_text": "Freddy",
        "answers": [{
            "answer_id": "1",
            "answer_text": "test1",
            "next_question": "ans02",
            "platforms": [{
                "platform_id": "1",
                "platform_name": "Facebook",
                "platform_weight": "0.5"
            }]
        },
        {
            "answer_id": "2",
            "answer_text": "test2",
            "platforms": [{
                "platform_id": "1",
                "platform_name": "Facebook",
                "platform_weight": "0.2"
            }]
        },        {
            "answer_id": "3",
            "answer_text": "test3",
            "platforms": [{
                "platform_id": "1",
                "platform_name": "Facebook",
                "platform_weight": "0.3"
            }]
        },        {
            "answer_id": "4",
            "answer_text": "test4",
            "platforms": [{
                "platform_id": "1",
                "platform_name": "Facebook",
                "platform_weight": "0.7"
            }]
        }]

}

我的插入函数是这样的:

  var input = req.body;
  var newAlgoData = new SurveySchema({
    question_id: input.question_id,
    question_text: input.question_text,
    answers: [input.answers],
    next_question: input.next_question,
    platforms: [input.answers.platforms]
  })
  console.log(newAlgoData);
  var isCreated = newAlgoData.save((function (err) {
    if (err){
      return false; 
    } else{
      return isCreated; 
    }
  }))

我得到的答复是:

{ _id: 5b79c144f0a8071048aa8f39,
  question_id: '1',
  question_text: 'Freddy',
  answers: [ { _id: 5b79c144f0a8071048aa8f3a, platforms: [] } ] }
(node:4168) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: newAlgoData.save(...) is not a function

我知道如何解决“不是函数”错误”,但是我的问题是将数据(特别是数组中的数据)插入db。

非常感谢您的帮助。

0 个答案:

没有答案