Created
October 21, 2018 14:38
-
-
Save tosipaulo/d6f23dc81ed6a555324988f097119efa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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