Building a MERN app and having issues with form submission
I’m working on a full stack project using MongoDB, Express, React, and Node. I have two models where one references the other, but when I submit my form to create a new record, I keep getting a 400 error.
My form component:
export default function CreateItemForm({handleNewItem, typesList}) {
const [itemData, setItemData] = useState({
title: "",
photos: [],
type: {typesList},
cost: 0,
details: ""
});
function updateField (event) {
setItemData({...itemData, [event.target.name]: event.target.value });
}
async function submitItem(event) {
event.preventDefault();
handleNewItem(itemData);
setItemData({
title: "",
photos: [],
type: {typesList},
cost: 0,
details: ""
});
}
return (
<div>
<h2>Create New Item</h2>
<form onSubmit={submitItem}>
<label>Title</label>
<input
name="title"
type="text"
value={itemData.title}
onChange={updateField}
required
/>
<label>Photos</label>
<input
name="photos"
type="text"
value={itemData.photos}
onChange={updateField}
required
/>
<label>Type</label>
<select
name="type"
value={itemData.type}
onChange={updateField}>
{typesList.map ((type, index) => (
<option key={index} value={type}>{type}</option>
))}
</select>
<label>Cost</label>
<input
name="cost"
type="number"
value={itemData.cost}
onChange={updateField}
required
/>
<label>Details</label>
<input
name="details"
type="text"
value={itemData.details}
onChange={updateField}
required
/>
<button type="submit">Create Item</button>
</form>
</div>
);
}
Main schema (trying to create):
const Schema = require('mongoose').Schema;
const itemSchema = new Schema({
title: { type: String, required: true },
photos: [{ type: String, required: true }],
type: {type: Schema.Types.ObjectId, ref: 'ItemType'},
cost: { type: Number, required: true },
details: { type: String }
}, {
timestamps: true
});
module.exports = itemSchema;
Referenced schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const itemTypeSchema = new Schema({
title: { type: String, required: true },
order: Number
}, {
timestamps: true
});
module.exports = mongoose.model('ItemType', itemTypeSchema);
Controller function:
async function addNew(req, res) {
try {
const newItem = await Item.create(req.body);
res.json(newItem);
} catch (error) {
res.status(400).json(error);
}
}
What am I doing wrong with the reference? The form sends data but the server throws 400 error. Any ideas what I’m missing?