Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const mongoose = require('mongoose')
- const validator = require('validator')
- const bcrypt = require('bcryptjs')
- const jwt = require('jsonwebtoken')
- const userSchema = new mongoose.Schema({
- username: {
- type: String,
- required: true,
- trim: true
- },
- email: {
- type: String,
- unique: true,
- required: true,
- trim: true,
- lowercase: true,
- validate(value) {
- if (!validator.isEmail(value)) {
- throw new Error('Email is invalid')
- }
- }
- },
- password: {
- type: String,
- required: true,
- minlength: 4,
- trim: true,
- },
- role: {
- type: String,
- required: true,
- },
- active: {
- type: Boolean,
- default: true
- }
- })
- userSchema.virtual('entries', {
- ref: 'Entry',
- localField: '_id',
- foreignField: 'owner'
- })
- userSchema.methods.toJSON = function () {
- const user = this
- const userObject = user.toObject()
- delete userObject.password
- return userObject
- }
- userSchema.methods.generateAuthToken = async function () {
- const user = this
- const token = jwt.sign({ _id: user._id.toString() }, 'secret')
- return token
- }
- userSchema.statics.findByCredentials = async (email, password) => {
- const user = await User.findOne({ email })
- if (!user) {
- throw new Error('Unable to login')
- }
- const isMatch = await bcrypt.compare(password, user.password)
- if (!isMatch) {
- throw new Error('Unable to login')
- }
- return user
- }
- // Hash the plain text password before saving
- userSchema.pre('save', async function (next) {
- const user = this
- if (user.isModified('password')) {
- user.password = await bcrypt.hash(user.password, 8)
- }
- next()
- })
- // Delete user tasks when user is removed
- userSchema.pre('remove', async function (next) {
- const user = this
- await Task.deleteMany({ owner: user._id })
- next()
- })
- const User = mongoose.model('User', userSchema)
- module.exports = User
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement