I used MVC to make a NodeJS server and this is one of the controllers:
module.exports.create_user = async function (req, res) { // console.log(req.body); // console.log(req.user); await Company.findOne({ user: req.body.user }, function (err, user) { if (user) { return res.redirect('/login'); } else { if (req.body.password == req.body.confirm_password) { Company.create({ "country": req.body.country, "username": req.body.user, "password": req.body.password }); } else { console.log('Passwords didnt match'); } } }); req.session.save(() => { return res.redirect('/profile'); }) }
What this code supposed to do?
It searches if a user already exists; if yes, it will redirect to /login
.
If no such user exists, it should create a new user and redirect to /profile
.
What does this code do?
Regardless of whether the user exists or not, the code always redirects to /login. Also, a user is created in the database, so every time a new user wants to signup, the user needs to signup and then go to sign in to get access to /profile
What is the problem here which doesn’t allow redirect to /profile
? And how to fix it?
Let me know if you need anything else
Answer
Use username
instead of user
to find a user
Company.findOne({ username: req.body.user });
You are mixing callback
style with async/await
, await
keyword does not affect on your, it will not wait until the query finished. await
keyword just working when you wait for a Promise like object
(then
able object).
I guess you are using mongoose
, the current version of mongoose
supports Promise return style.
module.exports.create_user = async function (req, res) { // console.log(req.body); // console.log(req.user); try { // Use `username` instead of `user` to find a user const user = await Company.findOne({ username: req.body.user }); // callback is not passed, it will return a Promise if (user) { return res.redirect('/login'); } if (req.body.password == req.body.confirm_password) { await Company.create({ // wait until user is created "country": req.body.country, "username": req.body.user, "password": req.body.password }); // then redirect page req.session.save(() => { return res.redirect('/profile'); }); } else { console.log('Passwords didnt match'); // what happen when password didn't match // return res.redirect('/login'); ??? } } catch (error) { // something went wrong // return res.redirect('/login'); ??? } }