我對 MongoDB 非常陌生,我正在測驗我的注冊/用戶路線以嘗試創建一個新用戶。我正在使用郵遞員。當我嘗試創建新用戶時,如果用戶已經存在,我會收到我設定的錯誤。但是,這是一個新用戶,檔案不在集合中。請有人告訴我哪里出錯了。
//Creating a new user
adminRouter.post('/register/user', async(req, res)=>{
const {email, password, company, role, firstName, lastName } = req.body;
console.log('email for new user: ', email);
//check if username already exists
const takenEmail = await Users.find({email: email});
if (takenEmail) {
res.status(400).json({message: "Email has already been used"})
} else {
const hashedPW = await bcrypt.hash(password,saltRounds);
await Users.create({
email: email,
password: hashedPW,
company: company,
role: role,
firstName: firstName,
lastName: lastName,
});
res.json({message: `SUCCESS: User ${email} created.`});
}
});
uj5u.com熱心網友回復:
在檢查用戶是否已經存在時,我終于通過使用 .findOne() 方法而不是 .find() 解決了我自己的問題。
adminRouter.post('/register/user', async(req, res)=>{
const {email, password, company, role, firstName, lastName } = req.body;
console.log('email for new user: ', email);
//check if username already exists
const takenEmail = await Users.findOne({email: email});
if (takenEmail) {
res.status(409).json({message: "Email has already been used"})
} else {
const hashedPW = await bcrypt.hash(password,saltRounds);
await Users.create({
email: email,
password: hashedPW,
company: company,
role: role,
firstName: firstName,
lastName: lastName
});
res.status(201).json({message: `SUCCESS: User ${email} created.`});
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/442441.html
