Skip to content

Instantly share code, notes, and snippets.

@mohanramphp
Created May 16, 2020 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohanramphp/2e50eaf69741b34c4f918a0e24d6ffc9 to your computer and use it in GitHub Desktop.
Save mohanramphp/2e50eaf69741b34c4f918a0e24d6ffc9 to your computer and use it in GitHub Desktop.
controller part for registration
const router = require("express").Router();
const User = require("../model/User");
const bcrypt = require("bcryptjs");
// validation
const { registerValidation, loginValidation } = require("../validation");
// register route
router.post("/register", async (req, res) => {
// validate the user
const { error } = registerValidation(req.body);
// throw validation errors
if (error) return res.status(400).json({ error: error.details[0].message });
const isEmailExist = await User.findOne({ email: req.body.email });
// throw error when email already registered
if (isEmailExist)
return res.status(400).json({ error: "Email already exists" });
// hash the password
const salt = await bcrypt.genSalt(10);
const password = await bcrypt.hash(req.body.password, salt);
const user = new User({
name: req.body.name,
email: req.body.email,
password,
});
try {
const savedUser = await user.save();
res.json({ error: null, data: { userId: savedUser._id } });
} catch (error) {
res.status(400).json({ error });
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment