Search code examples
javascriptmongodbmongoose

Mongoose: Optional fields marked as required


I have the following Schema in Mongoose:

const ReviewSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true,
    },
    text: {
        type: String,
        required: true,
    },
    stars: {
        type: Number,
        required: true,
    },
    author: {
        type: mongoose.Types.ObjectId,
        required: true,
        ref: "User",
    },
    recipient: {
        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,
});

As you can see comments is not required nor are its fields. However, when I make a request with Postman to an API that creates a review I get an error:

{
  "message": "Error: ValidationError: comments.author: Path `comments.author` is required., comments.text: Path `comments.text` is required."
}

Here's my API endpoint's code:

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),
        text: z.string().min(10).max(1000),
        stars: z.number().gte(1).lte(5),
        author: z.string(),
        recipient: z.string().min(5),
    });

    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,
            text: parsedRequest.text,
            stars: parsedRequest.stars,
            author: parsedRequest.author,
            recipient: parsedRequest.recipient,
        })
        return NextResponse.json({ message: "Successfully added a review" });
    } catch (error) {
        return NextResponse.json({ message: `Error: ${error}` }, { status: 500 });
    }
}


Solution

  • Try to change comments field declaration:

    const ReviewSchema = new mongoose.Schema({
        comments: {
            type: {
                text: {
                    type: String,
                },
                author: {
                    type: mongoose.Types.ObjectId,
                    ref: 'User',
                },
            },
            required: false,
        },
    });