I have a function which is supposed to return to me all the unanswered questions of a user. It uses a monogodb-Collection "Selection" to retrieve all the question_id's from questions the user hasn't answered yet.
This works perfectly fine, as long as the user has answered at least one question and the aggregation doesn't come back empty.
exports.showUnansweredByUser = async (req, res, next) => {
const user_id = req.params.user_id;
try {
const questionIds = await Selection.aggregate(
[
{
$match: {
"user_id": user_id
}
},
{
$unset: [
"user_id",
"selected_answer",
"_id",
"__v"
]
},
{
$group: {
"_id": "",
"question_id": {
$push: "$question_id"
}
}
}
]
)
if(questionIds !== null){
const idsArray = questionIds[0].question_id
console.log(idsArray)
}
/*if(idsArray !== null){
const unansweredQuestions = await Question.aggregate(
[
{
$addFields: { _id: { $toString: "$_id" }}
},
{
$match: { _id: { $nin: idsArray}}
}
]
)
res.json(unansweredQuestions)
} else {
console.log("all questions are unanswered.")
/!*const unansweredQuestions = await Question.aggregate(
[
{
$addFields: { _id: { $toString: "$_id" }}
}
]
)
res.json(unansweredQuestions)*!/
}*/
} catch (err){
res.json({message: "show by user is not working"});
}
}
My first idea was to just check if the resulting idsArray is empty or not (as shown in the commented out code).
My second try was to check if questionIds, the result of my "await Selection.aggregate(..." is empty.
I know suppose that the aggregation comes back "empty" and my async-await Promise is never fulfilled. But how do I handle this?
I want it to work when there is a answered question aka. the Selection has a result and if there is no answered question aka. the Selection comes back empty.