I am able to input data into other fields in mongoDB, however, I am unable to input the

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

Answer №1

Remember to use the hashed password after creating your account.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does Vue only change a specific array element without updating the DOM?

My curiosity is piqued by a puzzling issue with updating specific items in an array using Vue.js. The documentation cautions that: Due to limitations in JavaScript, Vue cannot detect the following changes to an array: When you directly set an item with th ...

What is the most effective method to exhibit every element within a content wrapper at a specific interval of time?

I am looking for a way to display each div within the content-wrapper after a specific time interval. Currently, I am using individual classes like el1, el2, el3, ... to accomplish this task. However, when dealing with content-wrappers containing multipl ...

Is there a way to pass a token variable from the main page to an iframe without relying on a post message?

I am seeking assistance on how to transfer a variable from a parent window to an iframe. My situation is as follows: I am working with 2 Angular5 applications named A and B . Application B is loaded within Application A using an iframe. The aut ...

Is my implementation of Model and Views in backbone.js accurate?

I'm new to backbone.js and I've just created my first page. I'm curious to know if I'm headed in the right direction with my approach (if there even is a "correct" way in software development). Is there a way to automatically bind mode ...

Is it possible to create a replicating text box in AngularJS that multiplies when entering input

I am experimenting with creating a sequence of text boxes that dynamically generate new empty text boxes as the user enters information into each one. Each text box is required to have an ng-model value associated with it, and they should all be generated ...

Waiting for Promise Js to be fulfilled

I've been exploring the use of Bluebird for handling promises in Node.Js. I have encountered a situation where I need a function to return only when a promise is fulfilled. The desired behavior can be illustrated by the following code snippet: functi ...

The state object in Next.js appears to be missing

const [ values , setValues ] = React.useState({ input_type: '', elements: [] }) const addOption = () => { let newElements = values.elements newElements.push({ type: "option", ...

Nodejs application encountering a problem with the findUser method in Active Directory

I have encountered an issue while using the activedirectory npm package with Nodejs v16.18.1. The code snippet below is used for authentication and finding user details: Could someone please assist with this? async authUserActiveDirectory(usernameAD: stri ...

Node.js captures the Promise and provides detailed feedback

As I embark on my journey with Node.js + Express, currently in the process of structuring my HTTP APIs, I have a controller that utilizes a specific pattern: my_controller.js 'use strict'; var AppApiFactory = function (express, appService) { ...

When processing a response from the backend (using express js), cookies are not being received in the browser while on localhost

I'm currently facing some difficulties with implementing authorization cookies within my application. Whenever I attempt to send a GET request to my API (which is hosted on port 8080) from my React frontend (running on port 3000), the cookies that I ...

"There is an issue with the payload size: request entity is too large. What is the solution for handling this in Nest

I am facing an issue where I need to send a request containing a large base64 string, approximately around 2 MB. However, the server keeps throwing an error message. How can I prevent this error from occurring: [Nest] 1666 - 11/01/2021, 1:50:58 PM ERRO ...

What is the best way to ensure bidirectional text appears correctly when two conflicting languages are combined, ensuring explicit directionality is set?

As I work on localization implementation, I encounter an issue with the directionality of mixed characters on the page. The text content is stored in a json file and inserted into the DOM using a Vue.js template. While individual characters display corre ...

I am unable to determine if I have already selected a List Item

My goal is to have a functionality where clicking on "Download Drivers" will open the list, and clicking again will close it. This should be achieved with onclick events only, no hover effects. Additionally, I want the list to remain open even if I click o ...

Is there a way to retrieve the chosen selection from a select dropdown element using JavaScript?

As someone who is still learning JavaScript, I've come across a particular issue. Within a webpage, there is a select dropdown as shown below: <select id="selTipoRap" class="form-control" th:field="*{tipoRappresentante}&qu ...

Experiencing a bug in Express, unable to dispatch the request

controllers/userController.js import User from '../models/userModel.js' import asyncHandler from 'express-async-handler' import generateToken from '../utils/generateToken.js' // @desc Authenticate user & obtain token / ...

Exploring the possibilities of jQuery with Accordion functionality and creating dynamic multiple menus

Incorporating the Wayfinder and Accordion menus, I have set up a two-level menu structure for the left column. The structure looks like this: <ul class="accordion">: Menu 1 Sub-menu 1.1 Sub-menu 1.2 Sub-menu 1.3 Menu 2 Sub-menu 2 ...

Stagnant className in map persisting despite changes being made

I am in the process of updating my react className based on changes to the active status within the sites variable, which is iterated over with a map function. The issue I'm facing is that the 'inactive' className persists even when the act ...

What is the best method to retrieve the value of a button that has been selected from a collection of buttons?

Within a functional component, there is an issue where the choose function keeps printing 'undefined'. I have utilized const [chosen, setchosen] = useState([]) within this code snippet. The full code has been correctly imported and the purpose of ...

Hiding a pop-up element and updating the state to False when clicking anywhere outside the element in the background

Presented here is my Search.js component. class Search extends Component { state = { doctors: [], showTab: false } openTab = () => { this.setState({showTab: true}); console.log('openTab state', this ...

Utilizing Express.js and AJAX to transfer JSON data from the server to the client

Having trouble sending JSON from Express.js back to the client, and I can't seem to figure out what's going wrong. routes/editor.js exports.save = function(req, res){ fs.readFile(__dirname + "/../public/index.html", function (err, data) { ...