Skip to content

Instantly share code, notes, and snippets.

@tosipaulo
Created October 21, 2018 14:38
Show Gist options
  • Save tosipaulo/d6f23dc81ed6a555324988f097119efa to your computer and use it in GitHub Desktop.
Save tosipaulo/d6f23dc81ed6a555324988f097119efa to your computer and use it in GitHub Desktop.
const express = require('express');
const User = require('../schema/User');
const router = express.Router();
router.post('/register', async (req, res) => {
const { email } = req.body;
try {
if(await User.findOne({email})){
return res.status(400).send({ error: 'User already exits' })
}
const user = await User.create(req.body);
user.password = undefined;
return res.send({user})
}catch (err){
return res.status(400).send( {error: 'Registration failed' + err})
}
})
module.exports = (app) => app.use('/auth', router)
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
unique: true,
required: true,
lowercase: true
},
password: {
type: String,
required: true,
select: false
},
createAt: {
type: Date,
default: Date.now
}
})
UserSchema.pre('save', async function (next) {
const hash = await bcrypt.hash(this.password, 10);
this.password = hash;
next();
})
const User = mongoose.model('User', UserSchema);
module.exports = User;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment