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

Is it possible to link multiple references to a single Element/Node?

I am working on a function component that needs to pass the incoming ref from the parent to a div it is rendering. Additionally, I want to create and assign a separate ref inside the component to the same div. However, due to an element only accepting one ...

Display 'Div 1' and hide 'Div 2' when clicked, then reveal 'Div 2' and hide 'Div 1' when a different button is clicked

I need help figuring out how to make two separate buttons work. One button should display 'Div 1' and hide 'Div 2', while the other button should show 'Div 2' and hide 'Div 1' when clicked. My knowledge of jquery an ...

Identifying sluggish GPU performance on a mobile device using three.js: A guide for developers

My game runs extremely slow on older mobile devices like the Samsung Galaxy S4 and iPhone 5 when shadows are enabled. However, when shadows are turned off, performance improves significantly. Is there a way to detect a slow GPU in order to disable sh ...

Error: There was a syntax issue when trying to parse JSON due to an unexpected identifier "object" in the anonymous function

I'm having trouble understanding why there was an issue parsing this file: { "t": -9.30, "p": 728.11, "h": 87.10 } This is the javascript code I used: <script type="text/javascript"> function verify() { $.get("http://....file.json", funct ...

The Utilization of Callback Functions in CRUD Operations

I am curious about incorporating CRUD operations as callbacks while maintaining the Separation of Concerns. For instance, I have written a function that retrieves all users: UserService.js function getUsers(callback) { User.find(function(err, users) { ...

JQuery is having trouble with playing multiple sound files or causing delays with events

I've been working on a project that involves playing sounds for each letter in a list of text. However, I'm encountering an issue where only the last sound file is played instead of looping through every element. I've attempted to delay the ...

Exploring the integration of Passport SAML authentication for a seamless experience across both the backend Node (Express) and client Vue

I have a unique situation where I have developed an application with a Node (Express) backend, and a Vue client. Recently, I decided to implement SAML Single Sign-On (SSO) using passport for authentication. While everything works perfectly within the Expre ...

Tips for transferring a JSON object from an HTML document to a JavaScript file

Here is the code snippet: <script id="product-listing" type="x-handlebars-template"> {{#each productsInCart}} <tr> <td> <div class="imageDiv"> <img ...

What is the best way to execute my node script with a shell script file?

Currently, I'm working on a personal website using node to help me organize the ebooks I'm reading. Right now, my process involves moving to the project folder and running node server.js. I had an idea to create a shell script so that all I hav ...

The clearfix feature is ineffective when using AngularJS

<ul class="dropdown-menu wm_search_div" ng-show="searchDivShow"> <li ng-repeat="user in searchUserList"> <a href="javascript:void(0);" class="wm_clearfix3"> <img ng-src="{{user.faceIcon}}" class="pull-left wm_se ...

The .forEach() method in Javascript is not suitable for DOM nodes as they are subject to change during the iteration

Having an issue with moving all DOM elements from one node to another, I initially used this code: div.childNodes.forEach((n) => me.container.appendChild(n)); However, I noticed that only half of the nodes were being copied. It seems that the problem ...

Is there a way to incorporate my JavaScript code into my page.jsx file efficiently?

Can I integrate this javascript code from a .js file into my .jsx file seamlessly? const { exportTraceState } = require("next/dist/trace"); const toggleBtn = document.querySelector('.toggle_btn') const toggleBtnIcon = document.querySe ...

Show a notification when utilizing AJAX requests

I consist of two separate files: one written in PHP and the other one in JavaScript and HTML. PHP file : <?php session_start(); //start session $_SESSION['data'] = "The content should be displayed as alert in the JS file"; JS/HTML File: & ...

Incorporating a <script> tag in Angular 8 to reference an external JavaScript file from a different website

I am currently using Angular 8 and its CLI to develop my website. Issue: I need to include an external JavaScript file from a different website by adding a <script> tag, for example: <script src="https://www.wiris.net/demo/plugins/app/WIRISplugin ...

What might be causing the ng-model in this plunkr to not update as expected?

I recently customized a ui-select plunkr to suit my specific needs. I've noticed that the ng-model is not updating as expected, but interestingly, clicking the button to update the model results in the ui-select getting updated. Any guidance on resol ...

The scripts are mistakenly interpreted as stylesheets, but are actually being transferred with the MIME type text/html

Encountering two console warnings while using Chrome: Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://domain/". domain/:11 Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://domain/". ...

What is the process for updating nodemailer to integrate with https (SSL) connections?

I'm in the process of setting up an Angular website, and I've encountered a roadblock with the contact form. Initially, the form was functional on the insecure version of the site. However, after implementing a URL rewrite rule to force users to ...

Angular tutorial: Organizing data by date only

This is my first time building an Angular app. I am fetching JSON data from an API using a factory service to get football match fixtures. My goal is to group these fixtures by date while disregarding the time component. The date string in the JSON is fo ...

Having trouble with selecting checkboxes in a div using jQuery? While it may work in IE and Firefox, Chrome seems to be causing issues

In my div, I have several checkboxes placed under labels for formatting purposes. There is a list of checkbox names that need to be checked upon certain actions. Here is the list: var columns= ['2','5','4'] This is the curren ...

"Learn how to retrieve and assign a value to a select2 dropdown in Vue.js

Currently, I am utilizing vuejs to create and delete dynamic select elements, which is functioning properly. To view the working example, please click here: https://jsfiddle.net/nikleshraut/fgpdp700/2/ var vm = new Vue({ el: "#app", data: { opt ...