我正在制作一个简单的留言板应用程序和一些逻辑,根据用户的电子邮件地址将某些用户的管理字段更改为 true。除了此功能之外,其他一切都按预期工作。
我解决这个问题的方法是向我的用户模型添加一个可选的管理字段,该字段的默认布尔值为 false。注册时,我的应用程序将查找预定的电子邮件,如果找到匹配项,则会将管理值更新为 true。这看起来很简单,但它不起作用。这是代码示例,以便您可以看到我的思考过程(我拿出了与这个问题相关的内容):
//This is my user registration logic
exports.register_post = asyncHandler(async (req, res, next) => {
try {
const admin = await User.findOne({email: process.env.ADMIN_EMAIL}).exec(); //find user based on the email they register will
if (admin) {
try {
const result = await admin.updateOne({ email: process.env.ADMIN_EMAIL }, { admin: true }).exec(); //update the
} catch (err) {
console.error('Error updating admin status:', err);
return res.status(500).send('Error updating admin status');
}
}
// Create new user
const user = new User({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: hashedPassword, // Use the hashed password
});
await user.save();
// Redirect after successful registration
res.redirect("/");
} catch (err) {
next(err);
}
});
const UserSchema = new Schema({
firstName: {type: String, required: true},
lastName: {type: String, required: true},
email: {type: String, required: true},
password: {type: String, required: true},
posts: {type: Schema.Types.ObjectId, ref: "Post"},
admin: {type: Boolean, default: false},
})
最让我困惑的是我的错误处理代码也没有被触发。它只是像我添加此功能之前一样创建用户。我能想到的唯一解决方案是在创建新用户后移动逻辑以更改管理字段。然而,这对我来说也不起作用。
我没有看到任何与正在注册的新用户相关的管理逻辑。
功能启动后,将
req.body.email
与 process.env.ADMIN_EMAIL
进行比较。如果为 true,则将 admin: true
值添加到您的用户初始值设定项并保存用户。
如果我误解了你的问题,我很抱歉,但这似乎是这样。