Inside a Node Route, I'm saving two documents, both of different models, but instead of getting saved in the order in the code (via top-down approach), they are getting saved in reverse order.
modelOneDoc.save().then((doc) => console.log('Model One Document saved'));
modelTwoDoc.save().then((doc) => console.log('Model Two Document saved'));
Output:
Model Two Document saved
Model One Document saved
Both Of the Model's Schema has a pre save call attached that does some calculation before saving the document. And I think that Its the pre calls that is disturbing the saving order.
Saving of ModelOneDoc before ModelTwoDoc is essential because ModelTwoDoc fetches ModelOneDoc in its pre save call. Help me solve the problem.
GitHub Repo here (Route: /exam/submit/:id)
EDIT: The Code Snippet is as follows:
request.body.questionAnswers.forEach((element, index) => {
var questionAnswer = new QuestionAnswer({exam: id});
examReturn.questionAnswers.push(questionAnswer._id);
questionAnswer.save().catch((error) => console.log(error));
});
examReturn.save().then(() => response.send('Exam Successfully submitted in Store'), (error) => response.status(400).send(error));
I have the First save call inside a loop, i expected that Second call (examReturn.save()) will be done after all the documents in the loop have been stored.
I cannot use the solution of nesting the model saving inside then calls here, as the Second model will be saved in first then call of loped documents.
Sorry for providing insufficient data earlier.