I'm I'm trying to create sub arrays with a mongoose and I have a dificulty to insert the subdocuments. My schema is like this:
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);
And the data that I want to insert into the db looks like this:
{
"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"
}]
}]
}
My insertion function is like this:
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;
}
}))
The responce I get is:
{ _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
I know how to fix the "not a function" error' ,but my problem is with the insertion of the data into the db, specifically the data in the arrays.
Thank you very much for your help.