I've been attempting to validate the request body against a Mongoose model that has 'required' validators, but I haven't been successful in achieving the desired outcome so far. My setup involves using Next.js API routes connected to MongoDB for handling requests.
Here is the structure of my model:
import { Document, Model, Schema, model, models } from "mongoose";
export interface ISimpleProject extends Document {
title: string;
headline: string;
summary: string;
img?: string;
github?: string;
url?: string;
}
const SimpleProjectSchema: Schema = new Schema({
title: { type: String, required: true },
headline: { type: String, required: true },
summary: { type: String, required: true },
img: { type: String },
github: { type: String },
url: { type: String },
});
export const SimpleProject: Model<ISimpleProject> =
models.SimpleProject || model("SimpleProject", SimpleProjectSchema);
Now, let's take a look at the request handler:
export default handleMethods()
.method<ModelWithID<ISimpleProject>>('POST', async (req, res) => {
await connectToMongoDB();
const body: ISimpleProject = req.body;
const newSimpleProject = new SimpleProject(body);
return newSimpleProject
.save()
.then((result) => {
res.status(200).json({ result: true, data: result });
})
.catch((e) => errorHandler(e, res));
})
.prepare();
}
To illustrate the issue, if I send a POST request with this body:
{
"title": "Hello World!"
}
I would expect to receive an error because both the headline
and summary
fields are missing. However, instead of getting a validation error, the response contains the saved document.