I am currently working on a task to locate and display all questions related to the "Question Collection" that are associated with all the surveys created by a specific user in the "Surveys Collection". Although I have successfully found questions for a particular survey in the list, my goal is to find all questions linked to various surveys.
Here is the progress I have made so far, wherein I am only able to find questions specific to one survey using the _id:
// Display list of user surveys
module.exports.displayUserSurveys = (req, res, next) => {
let id = req.user._id;
Survey.find({ User: id }, (err, surveyList) => {
if (err) {
console.log(err);
res.end(err);
} else {
let questionId = surveyList[0].Questions;
Question.find({ _id: questionId }, (err, questionList) => {
if (err) {
return console.error(err);
} else {
let currentDate = new Date();
res.render("content/survey/my-surveys", {
title: "My Surveys",
page: "my-surveys",
username: req.user ? req.user.username : "",
SurveyList: surveyList,
QuestionList: questionList,
today: currentDate,
});
}
});
}
});
};
Survey Schema:
let surveyModel = mongoose.Schema(
{
Title: String,
Type: [String],
Questions: { type: mongoose.Schema.Types.ObjectId, ref: "questions" },
Answered: { type: Number, default: 0 }, // how many times users answered
User: { type: mongoose.Schema.Types.ObjectId, ref: "users" },
startdate: { type: Date, default: Date.now },
enddate: { type: Date, default: Date.now() + 30 * 24 * 60 * 60 * 1000 }, //30 days to milliseconds to set default end date 30 days out
},
{
collection: "surveys",
}
);
Questions Schema:
let questionModel = mongoose.Schema(
{
MC: {
startdate: Date,
enddate: Date,
QuestionText1: String,
Options1: [String],
QuestionText2: String,
Options2: [String],
QuestionText3: String,
Options3: [String],
QuestionText4: String,
Options4: [String],
QuestionText5: String,
Options5: [String],
},
TF: {
startdate: Date,
enddate: Date,
QuestionText1: String,
Options1: Boolean,
QuestionText2: String,
Options2: Boolean,
QuestionText3: String,
Options3: Boolean,
QuestionText4: String,
Options4: Boolean,
QuestionText5: String,
Options5: Boolean,
},
},
{
collection: "questions",
}
);
Would this approach be successful?
// Display list of user surveys
module.exports.displayUserSurveys = (req, res, next) => {
let id = req.user._id;
Survey.find({ User: id }, (err, surveyList) => {
if (err) {
console.log(err);
res.end(err);
} else {
Survey.aggregate([
{ $match: { User: id }},
{
$lookup : {
from: "Question",
localField: "Questions",
foreignField: "_id",
as: "questions"
}
}
]).exec((err, questionList) => {
if(err) {
console.log(err);
res.end(err);
} else {
let currentDate = new Date();
res.render("content/survey/my-surveys", {
title: "My Surveys",
page: "my-surveys",
username: req.user ? req.user.username : "",
SurveyList: surveyList,
QuestionList: questionList,
today: currentDate,
});
}
});
}
});
};