I want to select raffle draw winners so for that based on certain conditions I've chosen the documents from Mongodb from which winners are to be chosen. Next, I need to generate random numbers based on the number of winners(Number of winners is taken from client side - React) and find the winners. But I also have to save the winners to the Mongodb database. I could do it for one winner but if the number of winner is more than one, how can I do this?
const chooseWinner = await Transaction.find(
{
ContCode: CountryCode,
CurrCode: CurrCode,
CorrOrgCode: CorrorgCode,
ServCode: ServCode,
BranchCode: BranchCode,
Trandate: {
$gte: FromDate,
$lte: ToDate,
},
},
"CustomerCode ReferenceNo Trandate NoOfWinners"
);
//to get no of docs
const docLength = Object.keys(chooseWinner).length;
console.log("length: ",docLength);
console.log(JSON.stringify(chooseWinner));
if(docLength == 0)
{
console.log("No winner");
res.status(400).send({ message: "winner not found" });
} else {
//to choose random winner
var random1 = Math.floor(Math.random() * docLength);
console.log("random no: ",random1);
try {
//adding raffle draw winner details to db
const updateRaffledraw = await Raffledraw.findOneAndUpdate(
{RaffleCategory : req.params.category},
{$set:
{ winners: {
CustomerCode: chooseWinner[random1].CustomerCode,
ReferenceNo: chooseWinner[random1].ReferenceNo
},
}
},
{multi : true}
);
} catch (err) {
res.status(400).send(err);
}
}