I'm a beginner who starts to learn node.js. In the middle of the way, I got a problem with a notification like this
{
"errors": {
"password": {
"name": "ValidatorError",
"message": "Path `password` is required.",
"properties": {
"message": "Path `password` is required.",
"type": "required",
"path": "password"
},
"kind": "required",
"path": "password"
},
"email": {
"name": "ValidatorError",
"message": "Path `email` is required.",
"properties": {
"message": "Path `email` is required.",
"type": "required",
"path": "email"
},
"kind": "required",
"path": "email"
},
"name": {
"name": "ValidatorError",
"message": "Path `name` is required.",
"properties": {
"message": "Path `name` is required.",
"type": "required",
"path": "name"
},
"kind": "required",
"path": "name"
}
},
"_message": "User validation failed",
"message": "User validation failed: password: Path `password` is required., email: Path `email` is required., name: Path `name` is required."}
This My User Model
const mongoose = require('mongoose')
const validator = require('validator')
const User = mongoose.model('User', {
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Email is invalid')
}
}
},
password:{
type: String,
required: true,
minlength: 7,
trim: true,
validate(value){
if (value.toLowerCase().includes('password')) {
throw new Error('Password cannot contain "password"')
}
}
},
age: {
type: Number,
default: 0,
validate(value) {
if (value < 0 ){
throw new Error('Age must be a positive number')
}
}
}
})
module.exports = User
With this user route
const express = require('express')
require('./db/mongoose')
const User = require('./models/user')
const Task = require('./models/task')
const app = express()
const port = process.env.PORT || 3000
app.use(express.json())
app.post('/users', async (req, res) => {
const user = new User(req.body)
try{
await user.save()
res.status(201).send(user)
} catch (e) {
res.status(400).send(e)
}
})
app.listen(port, () => {
console.log('Server is up on port' +port)
})
Does anyone understand why it would be happening?
Hope I get the answer in this forum to continue my study. Thank you in advance for your help guys. Really appreciate it.
As you have defined all these fields as required:true in your schema that's why its happening, you have to provide values to these fields i.e. while testing your api do fill these fields with some value in body.