I need a bit of help on this one; its more about verifying....
I'm trying to find out if the user's lastLoginDate has been exactly a year from today.
This is what I've done so far and I think it makes sense, however, I would like if somebody could tell me if there's something wrong.
I'm using this code to suspend the users account if their last login has been exactly 1 year.
exports.checkLastLoginDate = asyncHandler(async (req, res, next) => {
let oneYearAgo = new Date()
oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1)
let users = await User.find()
const filteredUsers = users.filter((user) => user.lastLoginDate <= oneYearAgo)
const inactiveUsers = filteredUsers.map(async (u) => {
await User.findByIdAndUpdate(
{ _id: u._id },
{
$addToSet: { role: 'suspended' },
},
{
new: true,
runValidators: true,
setDefaultsOnInsert: false,
}
)
})
res.status(200).json({ success: true, data: inactiveUsers })
})
Does it makes sense or do you guys think this is wrong?
CodePudding user response:
I think you should be able to optimize your code by using updateMany
instead of retrieving all users and filtering them in plain JS:
exports.checkLastLoginDate = asyncHandler(async (req, res, next) => {
let oneYearAgo = new Date();
oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
const inactiveUsers = await User.updateMany(
{ lastLoginDate: { $lte: oneYearAgo } },
{ $addToSet: { role: 'suspended' } },
{ new: true, runValidators: true, setDefaultsOnInsert: false }
);
res.status(200).json({ success: true, data: inactiveUsers });
});