I have a Mongoose Schema setup like this:
const PostSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
likes: {
type: Number,
required: true,
},
author: {
type: mongoose.Types.ObjectId,
required: true,
ref: "User",
},
comments: {
text: {
type: String,
},
author: {
type: mongoose.Types.ObjectId,
ref: "User",
},
},
createdAt: {
type: Date,
required: true,
default: () => Date.now(),
},
updatedAt: Date,
});
The interesting thing here is that the comments
field and its properties are not mandatory. Nonetheless, when I send a request through Postman to an API endpoint for creating a review, I encounter an error:
{
"message": "Error: ValidationError: comments.author: Path `comments.author` is required., comments.text: Path `comments.text` is required."
}
Let me share the code snippet of the API endpoint with you:
import { NextResponse } from "next/server";
import z from "zod";
import { Review, } from "@/mongo";
export async function PUT(request: Request) {
const rawRequest = await request.json();
const Schema = z.object({
title: z.string().min(5).max(20),
content: z.string().min(10).max(1000),
likes: z.number().gte(1).lte(5),
author: z.string(),
});
const parsedRequest: RequestType = rawRequest;
const valid = Schema.safeParse(parsedRequest);
type RequestType = z.infer<typeof Schema>;
if (!valid.success) {
return NextResponse.json(
{ message: `Error: ${valid.error}` },
{ status: 400 }
);
}
try {
await Review.create ({
title: parsedRequest.title,
content: parsedRequest.content,
likes: parsedRequest.likes,
author: parsedRequest.author
})
return NextResponse.json({ message: "Review added successfully" });
} catch (error) {
return NextResponse.json({ message: `Error: ${error}` }, { status: 500 });
}
}