使用 node.js 和貓鼬,我有一個基本的/login
路線。在資料庫中,有一個布爾active: true|false
狀態屬性。當用戶使用/deleteme
route it to洗掉他們的帳戶active: false
并且用戶使用 schema.pre 中間件 /^find/ 時無處出現。但是我想在他們嘗試登錄時重新激活用戶的帳戶。但這不起作用,因為無法找到用戶,因為預中間件阻止使用任何查找方法找到用戶。
長話短說,我可以為我的 schema.pre 中間件創建一個例外,如果它被特定的中間件呼叫它就不會被執行?
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);
});```
uj5u.com熱心網友回復:
你可以使用updateOne
方法。
exports.deleteMe = catchAsync(async (req, res, next) => {
await User.updateOne({_id: req.user.id}, { active: false });
res.status(204).json({
status: 'success',
data: null,
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/504017.html
上一篇:聚合以過濾MongoDB中的參考