This's my first time using MongoDB. I'm making REST API on server side with Node.Js, all this API totally works fine on my Postman. I have no trouble when I tried to input a value to MongoDB from Text Field but when I'm used Select Box the troubles come & I'm stuck with this, please help.
Error That I got
AxiosError code: "ERR_BAD_REQUEST", message: "Request failed with status code 400", data: {message: 'User validation failed: gender: Path `gender` is required.'}
My Select Box
<div className='form-group col'>
<select
value={gender}
onChange={(e) => setGender(e.target.value)}
required>
<option disabled selected aria-hidden>--Select Gender--</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
My Save Function
const saveUser = async (e) => {
e.preventDefault();
try {
await axios.post("http://localhost:4000/user", {
name,
email,
gender
});
navigate("/lists")
} catch (error) {
console.log(error);
}
}
My API Function
export const saveUser = async (req, res) => {
const user = new User(req.body);
try {
const inserteduser = await user.save();
res.status(201).json(inserteduser);
} catch (error) {
res.status(400).json({message: error.message});
}
}
My DB Model
import mongoose from "mongoose";
const User = mongoose.Schema({
name:{
type: String,
required: true
},
email:{
type: String,
required: true
},
gender:{
type: String,
required: true
}
});
export default mongoose.model('User', User);
I have no trouble when tried to pass some value using text field, but I think because I'm using Select Box. Maybe there's something I've been missing or wrong let me know.
CodePudding user response:
I just fixed this. The problem is the value that had been pass from the select box is empty. So I store the data first with another const
.
const to store the data temporary
const [data, setData] = useState({
name: '',
email: '',
gender: ''
});
And the function to handle the onchange event
function handle(e) {
const newData = { ...data };
newData[e.target.id] = e.target.value;
setData(newData);
console.log(newData);
};
And this how I pass the value from the data array
const saveUser = async (e) => {
e.preventDefault();
try {
await axios.post("http://localhost:4000/user", {
name: data.name,
email: data.email,
gender: data.gender
})
.then(console.log(data));
navigate("/lists")
} catch (error) {
console.log(error);
}
}
This how I get the value from the select box
<select
id='gender'
className="form-select form-select-sm"
value={data.gender}
onChange={(e) => handle(e)}
required>
<option selected hidden>--Select Gender--</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>