I am facing an issue with the password while everything else seems to be working fine. I am using a schema and getting an error, but it could be a problem in my functions because I hashed the password. I am unable to identify what's causing the issue.
My server
const express = require('express')
const colors = require('colors')
const dotenv = require('dotenv').config()
const {errorHandler} = require('./middleware/errorMiddleware')
const connectDB = require('./config/db')
const PORT = process.env.PORT || 5000
//connect to database
connectDB()
const app = express()
app.use(express.json())
app.use(express.urlencoded({extended: false}))
app.get('/', (req, res) => {
res.status(200).json({message: 'Welcome to the support desk api'})
})
app.use('/api/users', require('./routes/userRoutes'))
app.use(errorHandler)
app.listen( PORT, () => console.log(`Port started on ${PORT}`))
My mongoose schema
const mongoose = require('mongoose')
const userSchema = mongoose.Schema({
name : {
type: String,
required: [true, 'Please enter your name']
},
email : {
type: String,
required: [true, 'Please add an email'],
unique: true
},
password : {
type: String,
required : [true, 'Please add a password'],
},
isAdmin : {
type: Boolean,
required : true,
default: false,
}
},
{
timestamps: true
})
module.exports = mongoose.model('User', userSchema)
My model where I use functions for registering login
const asyncHandler = require('express-async-handler')
const bcrypt = require('bcryptjs')
const User = require('../models/userModel')
// @desc register a new user
// @ route api/users
// @acess Public
const registerUser = asyncHandler(async (req, res) => {
const {name, email, password} = req.body
//validation
if(!name || !email || !password) {
res.status(400)
throw new Error('Please iclude all fields')
}
//find if user already exist
const userExists = await User.findOne({email})
if (userExists){
res.status(400)
throw new Error('User already Exist')
}
//hash password
const salt = await bcrypt.genSalt(10)
const hashedPassword = await bcrypt.hash(password, salt)
//create user
const user = await User.create({
name,
email,
hashedPassword,
})
if(user) {
res.status(201).json({
_id: user._id,
name: user.name,
email: user.email
})
} else {
res.status(400)
throw new Error('Invalid user Data')
}
})
// @desc register a new user
// @ route api/users/login
// @acess Public
const loginUser = asyncHandler(async (req, res) => {
res.send('Login Route')
})
module.exports = {
registerUser,
loginUser
}
My result from Postman Result from Postman