Basically I have two collections with one two many relationship question and answers i am trying to populate data these related collections.
Once the question is saved, I am trying to save multiple answers related to that question. Here is the code that i have written so for to add multiple answer(where answers is a array containing object inside).
let question = await Question.findOne({_id: question_id});
//Here answer is a array containing objects
answers.forEach(async function (answer, i) {
let newAnswer = new Answer({
question: question._id,
answers: answer.ans,
});
await newAnswer.save();
await question.answers.push(newAnswer);
await question.save();
});
However this code saves only one reference to the question collection and throws error
"Can't save() the same doc multiple times in parallel. Document: 5bf7cb66f4f14a5bb6a2bf6c {"name":"ParallelSaveError"}"
Please help me to find out the correct method to solve this problem thanks.
Here is the Model
const questionSchema = mongoose.Schema({
question: {
type: String,
required: true,
unique: true
},
answers: [{type: mongoose.Schema.ObjectId, ref: 'Answer'}]
});
const answerSchema = mongoose.Schema({
question: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Question'
},
answers: {
type: String,
required: true
}
});