I want to execute a schema statistics as post findOneAndDelete middleware in mongoose. My code is calling the schema when I am looping over but it just calculate for only one document deletion.
I have searched over many question and answer but didn't work yet,
exports.deleteAllAssociatedAns = catchAsync(async (req, res, next) => {
const allAssocAnswers = await Answer.find({
answerOfQuesId: req.params.quesId,
});
if (!allAssocAnswers || allAssocAnswers.length === 0) {
next();
}
await Promise.all(
Array.from(allAssocAnswers).map(async (el) => {
const deletedAnswer = await Answer.findOneAndDelete({
_id: el._id,
});
if (!deletedAnswer) {
return next(new AppError('Something Went Wrong, Try Again!', 404));
}
})
);
//Next Middleware
});
FindOneAndDelete then call a schema statistics,
answerSchema.statics.calcUserAnswerStatistics = async function (
userId,
status
) {
const stats = await this.aggregate([
{
$match: { answerAuthor: userId },
},
{
$group: {
_id: '$answerAuthor',
nAnswers: { $sum: 1 },
},
},
]);
if (stats.length > 0) {
const user = await User.findById(userId);
const userPoints = user.earnedPoints;
const qnaCount = user.totalQnaCount;
console.log(userPoints); **//This is consoling 4 Times If there is 4 Result but the below calculation is just calculating one time**
if (status === 'new') {
user.earnedPoints = userPoints + 5;
user.totalQnaCount = qnaCount + 1;
user.givenAnswersCount = stats[0].nAnswers;
} else {
user.earnedPoints = userPoints - 5; **//Just Decrease Ones**
user.totalQnaCount = qnaCount - 1; **//Just Decrease Ones**
user.givenAnswersCount = stats[0].nAnswers;
}
await user.save({ validateBeforeSave: false });
} else {
await User.findByIdAndUpdate(userId, {
givenAnswersCount: 0,
});
}
};
answerSchema.post(/^findOneAndDe/, async function () {
const ansOfQues = await Question.findById(this.r.answerOfQuesId);
ansOfQues.answerCount -= 1; **//If there is Four Time Calls Count Should Decrease 4 in total but problem is it just decreasing one**
await ansOfQues.save({ validateBeforeSave: false });
await this.r.constructor.calcUserAnswerStatistics(
this.r.answerAuthor,
'deleted'
); **//This method is called 4 times but calculate only ones**
});