Skip to content
Snippets Groups Projects

Resolve "Add random question controller"

Merged Pedro Pablo Cardona Arroyave requested to merge 145-add-random-question-controller into main
2 files
+ 76
1
Compare changes
  • Side-by-side
  • Inline
Files
2
@@ -150,8 +150,75 @@ async function getRandomQuestionsByCategory(category_id, count) {
}
}
async function getRandomQuestions(count) {
let client;
try {
client = await connectToDatabase();
const db = client.db("TrioTech");
const questionCollection = db.collection("questions");
// Calculate the number of questions to fetch for each difficulty level
const totalQuestions = count;
const countDifficult0 = Math.floor(0.4 * totalQuestions);
const countDifficult1 = Math.floor(0.3 * totalQuestions);
const countDifficult2 = totalQuestions - countDifficult0 - countDifficult1;
// Define the aggregation pipeline to select questions based on difficulty
const pipeline = [
{
$match: {
$and: [{ difficult: 0 }],
},
},
{
$sample: { size: countDifficult0 },
},
{
$unionWith: {
coll: "questions",
pipeline: [
{
$match: {
$and: [{ difficult: 1 }],
},
},
{
$sample: { size: countDifficult1 },
},
],
},
},
{
$unionWith: {
coll: "questions",
pipeline: [
{
$match: {
$and: [{ difficult: 2 }],
},
},
{
$sample: { size: countDifficult2 },
},
],
},
},
];
const response = await questionCollection.aggregate(pipeline).toArray();
return response;
} catch (error) {
throw error;
} finally {
if (client) {
await client.close();
}
}
}
module.exports = {
createQuestion,
getQuestion,
getRandomQuestionsByCategory,
getRandomQuestions,
};
Loading