Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

238
Vistas
how to fix this is node"Error: User validation failed: username: Path `username` is required. password: Path `password` is required."

I'm creating a new user and checking whether the user email previously exists or not. If not then it is creating a new user and saving it. What do I need to correct this validation error I am getting?

I have already tried by setting name as not required. But it still does not work.

This is my User model.

User.js

import mongoose from 'mongoose'

const UserSchema = new mongoose.Schema(
    {
      username: {
        type: String,
        required: true,
        unique: true,
      },
      email: {
        type: String,
        required: true,
        unique: true,
      },
      password: {
        type: String,
        required: true,
      },
      profilePic: {
        type: String,
        default: "",
      },
    },
    { timestamps: true }
  );

const User = mongoose.model("User",UserSchema)
export default User

this is my router file

import User from '../model/User.js'
import express from 'express'

const router = express.Router()

//register
router.post("/register",async (req,res) => {
    try{
        const newUser = new User({
            username:req.body.username,
            password:req.body.password,
            email:req.body.email
        })

        const user =await newUser.save()
        res.status(200).json(user)
    }catch(err){
        res.status(500).json(err)
    }
})

export default router

this is my app.js

import express from 'express'
import mongoose from 'mongoose'
import dotenv from 'dotenv'
import UserRoute from './routes/User.js'

const app = express()
dotenv.config()
app.use(express.json())
app.use(express.urlencoded({ extended: true }));

const PORT = process.env.PORT || 3000

mongoose
  .connect(process.env.MONGO_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then(console.log("Connected to MongoDB"))
  .catch((err) => console.log(err));

app.use("/api/auth",UserRoute)

app.listen(PORT , () => console.log(`backend started on ${PORT}` ))

i also just notice one thing if i tries to bcrypt the password and then use it in my route then after making request in postman instead of error message i am getting null object {} in postman what's the reason ???

what is the issue on the code i tried different ways to fix this by taking reference from stack overflow but didn't work

thanks for your help

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

How is your request body look like? Are you sure there are req.body.username and req.body.passwords? Try console.log them before you save the user and check they are not undefined.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda