Mongoose: Imposing Requirements on Optional Fields

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 });
        }
    }

    

Answer №1

Consider modifying the comments field definition:

const FeedbackSchema = new mongoose.Schema({
    comments: {
        content: {
            type: String,
        },
        reviewer: {
            type: mongoose.Types.ObjectId,
            ref: 'User',
        },
        required: false,
    },
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for transferring data to a child component's @Input using Observables

I've created an angular component that serves as a tab within a for loop on my HTML page: ... <ng-container *ngFor="let tabData of data$ | async;"> <tab-component id="{{ tabData.id }}" name="{{ tabData.name }} ...

Redux state not reflecting changes until second click

My redux store has a simple boolean setup to track whether a sidebar is expanded or not. However, I'm encountering an issue where, even though the default value is false, clicking the toggle button outputs false first. Ideally, if it's initially ...

Design a dynamic table using JavaScript

After spending hours working on my first JavaScript code, following the instructions in my textbook, I still can't get the table to display on my webpage. The id="eventList" is already included in my HTML and I've shortened the arrays. Here' ...

Using jQuery to update the input value when the mouse hovers over a div

Attempting to update an input value using jQuery mouseover. Situation: There are 5 divs with different colors and usernames. When hovering over a div, the input text (and background color for the color input) changes based on database values. Each time a ...

I encountered difficulty executing a nodejs child_process on my Amazon EC2 instance

I'm utilizing the nodejs child_process function spawn() to execute a mongoexport. I have provided all the necessary parameters to the command and it's functioning correctly on my local setup. Below is the code snippet for the function: userDetai ...

I am looking to modify various attributes linked to Rails

My Desire for Reality I am looking to update multiple related values in Rails by sending an update request from JavaScript. While creating data was seamless, I encountered difficulties when attempting to update it. #Code JavaScript* export const actions ...

Adjust the size at the location of the cursor

I am having trouble understanding how to implement zoom based on mouse position using this example here: (https://stackblitz.com/edit/js-fxnmkm?file=index.js) let node, scale = 1, posX = 0, posY = 0, node = document.querySelector('.f ...

Having trouble removing an object from an array using $pull method?

I am currently facing a challenge when it comes to deleting a lesson with a specific lesson_id from the following data. { "_id" : ObjectId("5807f3f"), "title" : "Title", "lessons" : [ { "lesson_id" : ObjectId("58073"), ...

I am having trouble having a select component populate with new child components while still maintaining its original value

So here's the situation. Let me simplify things for you. I'm in the process of developing an app that generates JSON queries to be sent to a server. The query-building components are structured in a nested manner: QueryContainer > QueryGroup ...

"Encountering an incorrect password while trying to log in using Node.JS, Passport,

I've been following a tutorial on NodeJS, Passport, and Sequelize and so far it's been going well. The sign-up part is working as expected. However, I've run into an issue where logging in with an incorrect password still results in a succe ...

Using the Jquery accordion function within google maps is limited to running only one time

After successfully creating a google maps page with markers generated from XML, I encountered an issue. The plan was to display event information in a div when a marker is clicked, along with attaching an accordion to the events data. Although the first cl ...

After a PHP script is executed, a Bootstrap modal will automatically appear on the same page

Seeking assistance with integrating a bootstrap modal into a contact form submission. Despite multiple attempts, I have been unsuccessful in achieving this integration and now find myself at an impasse. My objective is simple: Upon clicking the submit bu ...

Display additional javascript code for expanding a marquee

Currently, I am working on a stock ticker project using JavaScript. It's progressing well, and now I am focusing on adding a "show more" button to style the ticker. The button should be placed outside of the marquee. When clicked, it will expand the m ...

Bring in items and then go through each one

I'm curious if there's a way to loop through imported objects? import { Row, Col, Form, FormItem, Icon, Input, Tooltip, Image, Button, Dialog } from 'element-ui' objects.forEach(object => { // do something here }) When I have a ...

Exclude the HTML attribute prior to displaying

Is there a way to prevent the src attribute from being used for each img tag until after a certain action is completed? I am trying to modify how images are fetched. Here's what I tried: $('img').each(function() { var elem = $(this); ...

In the event that the `algorithms` option is not defined, an error will be thrown stating that `algorithms` must be specified: `Error: algorithms should be

Currently, I am diving into the world of Nodejs, but I have hit a roadblock in my learning journey. I recently installed a new library from npm called express-jwt, but it seems to be throwing an error when I try to run it. Below is the snippet of my code a ...

What is the reason behind a number having its final two digits transformed into zeros?

Query Hello, I was coding my discord bot and storing user IDs in a database. I plan to use these IDs to ping or assign roles to users. Issue However, I encountered a problem where the IDs in the database are being altered. For example, from 5336929053871 ...

What steps should I follow to integrate AJAX with jQuery in order to store Summernote text in a database?

Seeking clarity on implementing Ajax with Jquery in a web app. I am new to programming with Jquery and struggling to understand existing explanations. I have a summernote text editor where users type values that I want to save in a database. Can someone pr ...

Solving Problems with Inline Tables using Angular, Express, and Mongoose's PUT Method

For the past few days, I've been struggling to figure out why my PUT request in my angular/node train schedule application isn't functioning properly. Everything else - GET, POST, DELETE - is working fine, and I can successfully update using Post ...

How to confirm the parent state in Angular's UI router?

In summary, I am seeking a function similar to state.is() that can verify a state with multiple child states from one of those child states? This is the structure I have: Parent 1 Child 1.1 Child 1.2 Child 1.3 Parent 2 Child 2.1 ...