mongodb Post Request Axios

e5nqia27  于 2022-12-12  发布在  Go
关注(0)|答案(1)|浏览(112)

I am getting this error:

Error: User validation failed: phone: Path `phone` is required., email: Path `email` is required., lname: Path `lname` is required., fname: Path `fname` is required.
    at ValidationError.inspect (C:\Users\hanzl\OneDrive\Desktop\CRUD\server\node_modules\mongoose\lib\error\validation.js:50:26)

REACT CODE:

const[data,setData]=useState({
        fname:'',
        lname:'',
        email:'',
        phone:''
    })

    const inputValues=(e)=>{
      var name=e.target.name
      var value=e.target.value
      setData(({...data,[name]:value}))
    }

    console.log(data)

    const addData=async (e)=>{
      e.preventDefault()
      try{
        const user=JSON.stringify(data)
        const res= await axios.post("http://localhost:6100/user/new",{user}).then((res)=>{console.log(res)})
      }catch(err){
        console.log(err)
      }
    }

SERVER CODE:

app.use(express.json())

app.use(cors())
app.use('/user',UserRoute)
const UserSchema=mongoose.Schema({
    fname:{
        type:String,
        required:true
    },
    lname:{
        type:String,
        required:true
    },
    email:{
        type:String,
        required:true
    },
    phone:{
        type:String,
        required:true
    }
})
router.post('/new',async (req,res)=>{
    try{
        const data= new User(req.body)
        await data.save()
        res.status(200).json(data)
    }catch(err){
        console.log("Data Not created ")
        console.log(err)
    }
})

I get error every time i try to do post request through axios. Whenever i remove required:true from schema. Empty object is stored in database. What is the solution for this problem, Kindly guide me through

zlhcx6iw

zlhcx6iw1#

如果要支持空字符串,请更改验证

const UserSchema=mongoose.Schema({
    fname:{
        type:String,
        required:isMyFieldRequired
    },
    lname:{
        type:String,
        required:isMyFieldRequired
    },
    email:{
        type:String,
        required:isMyFieldRequired
    },
    phone:{
        type:String,
        required:isMyFieldRequired
    }
})

function isMyFieldRequired () {
    return typeof this.myField === 'string'? false : true
}

相关问题