I am very new to MongoDB and I am testing my register/user route to try to create a new user. I'm using Postman. When I try to create the new user, I am getting the error that I set if the user already exists. However this is a new user and the document is not in the collection. Please could someone tell me where I am going wrong.
//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.`});
}
});
CodePudding user response:
I finally solved my own problem by using the .findOne() method rather than .find() when checking whether the user already exists.
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.`});
}
});