Home > OS >  Can I create an exception for pre middleware
Can I create an exception for pre middleware

Time:09-03

Using node.js and mongoose, I have a basic /login route. In the database, there is a boolean active: true|false state property. When a user deletes their account using /deleteme route it to active: false and the user appears nowhere using schema.pre middleware /^find/. But I want to reactivate the user's account whenever they try to log in. But it won't work because the user can't be found since the pre-middleware prevents the user to be found using any find method.

So long story short, can I create an exception to my schema.pre middleware that it will not get executed if it gets called by a specific middleware?

router.post('/login', authController.login);
router.delete('/deleteMe', userController.deleteMe);
userSchema.pre(/^find/, function (next) {
  this.find({ active: { $ne: false } });
  next();
});
exports.deleteMe = catchAsync(async (req, res, next) => {
  await User.findByIdAndUpdate(req.user.id, { active: false });

  res.status(204).json({
    status: 'success',
    data: null,
  });
});
exports.login = catchAsync(async (req, res, next) => {
  const { email, password } = req.body;

  if (!email || !password) {
    return next(new AppError('Please provide email and password', 400));
  }

  const user = await User.findOne({ email }).select(' password');

  if (!user || !(await user.correctPassword(password, user.password))) {
    return next(new AppError('Incorrect email or password', 401));
  }

  await User.findByIdAndUpdate(user.id, { active: true });
  createSendToken(user, 200, res);
});```

CodePudding user response:

You can use updateOne method.

exports.deleteMe = catchAsync(async (req, res, next) => {
  await User.updateOne({_id: req.user.id}, { active: false });

  res.status(204).json({
    status: 'success',
    data: null,
  });
});
  • Related