I'm trying to add mongoose Id's to my 2 arrays, but it comes back as empty arrays. I can't seem to find what's wrong here is my function,
exports.create = (body) => {
console.log(body.projectName);
const theDate = getDate();
qpTemplate.findOne().sort({version: -1}).exec(function(err, doc) {
var answerArray = [];
var questionArray = [];
var newProject = new projectModel({
_id: id(),
owner: Id,
projectName: body.projectName,
date: theDate,
version: 1.0,
});
var qp = new questionPackageModel ({
_id: id(),
version: 1,
questionIds: [], // this one i want to populate
projectId: newProject._id
});
console.log("hej")
doc.questionIds.map(theId => {
questionTemplate.findById(theId, function (err, question) {
var theQuestion = new questionModel({
_id: id(),
qpId: qp._id,
categoryId: question.categoryId,
order: question.order,
version: question.version,
question: question.question,
answerIds: [], // this one i want to populate
name: question.name,
legacyName: question.legacyName,
description: question.description
})
question.answerIds.map(answerId => {
answerTemplate.findById(answerId, function (err, answer) {
var theAnswer = new answerModel({
_id: id(),
questionId: theQuestion._id,
name: answer.name,
order: answer.order,
answerText: answer.answerText,
value: answer.value,
placeholder: answer.placeholder,
settings:answer.settings,
description: answer.description
})
theQuestion.answerIds.push(theAnswer._id); // returns an empty array at the end
answerArray.push(theAnswer);
theAnswer.save();
});
})
qp.questionIds.push(theQuestion._id); // returns an empty array in the end
questionArray.push(theQuestion);
theQuestion.save()
});
})
newProject.qpId = qp._id;
qp.save();
newProject.save();
console.log(questionArray);
console.log(newProject)
return(items={answerArray,questionArray,qp,newProject})
})
}
What i'm trying to accomplish is to connect the models to eachother with their ids that's why I'm adding their id's to the array. I don't want the whole object in there since i'm then pushing this data to a redux client that require a flat state.
** I'm thankful for every answer! **