I am building an auto task manager that will automatically assign a task to users with the same role as the role of the task. Right now I am getting the total number of users with the same role as the task and then use math.random() to generate a number from 0 to the length of the users that have the same role and the assign the task to that random user. This isn't efficient as a user can have 10 tasks and another user has just 4 tasks. Is there a way I can assign tasks sequentially to all the users with the same role with the task??
This is the code to that creates a new task:
exports.createNewTask = async (req, res) => {
try {
let task = new Task({
title: req.body.title,
description: req.body.description,
role: req.body.role,
priority:req.body.priority
});
let role = req.body.role;
let user = await User.find({ role: role });
if(user.length == 0) {
res.status(500).json({message:"Please Create a User With this role" });
}
let random = Math.floor(Math.random() * user.length);
let assignedUser = user[random]._id;
task.user = assignedUser;
let assignedTask = await task.save()
res.status(200).json({ assignedTask });
} catch (err) {
console.log(err);
res.status(500).json({ error: err });
}
};