The 'required' validator in Mongoose seems to be malfunctioning

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.

Answer №1

It's interesting to note that by upgrading mongoose from 6.2.5 to 6.2.9, the issue was resolved effortlessly.

To update to the latest version, simply execute yarn remove mongoose followed by yarn add mongoose.

After upgrading, validations are now functioning as expected. Don't forget to restart your development server to see the changes take effect.

I have a hunch that the old model may have been cached (although I'm unsure if this is standard behavior in mongoose), hence why everything started working correctly after restarting the server.

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

A guide on defining global TypeScript interfaces within Next.js

In the process of developing an ecommerce web application with next.js and typescript, I found myself declaring similar interfaces across various pages and components. Is there a method to create global interfaces that can be utilized by all elements wit ...

Exploring alternative applications of defineModel in Vue 3.4 beyond just handling inputs

The examples provided for defineModel in the Vue documentation primarily focus on data inputs. I was curious if this functionality could be utilized in different contexts, potentially eliminating the need for the somewhat cumbersome props/emit approach to ...

The issue with the react-diagram stemmed from a conflict with @emotion/core

During the installation of react-diagrams by projectStorm, I encountered some errors which are shown in the following image: errorImg Despite attempting to downgrade the version of '@emotion/core' to ^10.0.0, the issue persisted. Here is a view ...

Guide on deploying a NextJs frontend with Golang (Go) and gorilla/mux

After following a guide to serve a NextJs front-end single-page application using Golang and the native net/http package, I decided to switch to using gorilla/mux. Here is my updated main function: func main() { // Root at the `dist` folder generated ...

Next-Auth | In cases where the user object contains an excessive number of items, the session request will be processed without

I will do my best to explain the issue that I am facing. Currently, I am using Strapi for backend and Nextjs for frontend development. To handle authentication, I have implemented NextAuth. [...nextauth].js: const options = { providers: [ Provider ...

What steps should I take to fix the Typescript error showing up in my Next.js route?

import type { NextApiRequest, NextApiResponse } from "next"; import db from "../../app/libs/dbConn"; interface DataProps { auth: [ { name?: string; email?: string; passwordHash?: string; } ]; status: n ...

Exploring MongoDB through proxyquire

To simulate a MongoDB dependency using proxyquire in my testing scenario, I have the following code snippet: var proxyquire = require('proxyquire'); var controller = path.resolve('.path/to/controller/file.js'); inside the before each ...

Getting session cookies in getServerSideProps with next js and firebase

In my current Next.js project, I am utilizing Firebase for authentication. To manage the user session, I am creating a session cookie using the Firebase admin SDK within an express backend API that is running on localhost but on a different port. const coo ...

Unable to locate module 'fs'

Hey there, I'm encountering an issue where the simplest Typescript Node.js setup isn't working for me. The error message I'm getting is TS2307: Cannot find module 'fs'. You can check out the question on Stack Overflow here. I&apos ...

Creating reducers for a unique data type: A step-by-step guide

Today, I was working on enhancing a shopping website using React Typescript and Context API. My goal is to utilize React Reducers to manage the state of my Shopping Cart. I have custom Types defined for the Product type, which includes an Items Array and s ...

Different Levels of Dynamic Routing in Next.js

I am a beginner learning about next.js. I'm curious to know how I can implement two levels of dynamic routing in next.js? The URL structure I want to achieve is http://localhost:3000/company/[slug1]/[slug2] After going through the official documenta ...

Interactive form control for location details including country, state, district, and town

I am struggling with adding dynamic form controls on dropdown change. I have been able to add them, but encountered an error preventing me from retrieving the value in 'formName.value'. The specific error message states: "Error: There is no Form ...

Encountering minor challenges with setting up MongoDB replica set on Windows platform

Currently, I am operating within the Windows 10 environment and aiming to set up a Replica Set on MongoDB. However, I have encountered some challenges during this process. To address these issues, I have extensively researched various tutorials to success ...

Issue with Stenciljs custom event not triggering using @Listen decorator

I've been trying to grasp the workings of the custom event emitter. While my mouse events seem to be functioning properly, I'm encountering issues with the custom events. Despite emitting correctly, it appears that the listener is not capturing t ...

The code inside the promise .then block is executing long before the promise has completed its

After spending quite some time working on this messy code, I finally have a functioning solution: loadAvailabilities() { let promises = []; let promises2 = []; let indexi = 0; //return new Promise((resolve, reject) => { this.appo ...

Verify and retrieve information from the Dynamics CRM Web API with the help of Angular 2 (TypeScript)

How can one authenticate and query the Dynamics CRM Web API from a Single Page Application developed with Angular 2 (TypeScript)? Initial research indicates that: The Dynamics CRM (version 2016 or 365) instance needs to be registered as an application ...

I'm curious as to why my t() texts are not updating in localhost/en after using i18n.changeLanguage(), but are refreshing correctly in localhost/fr

Hello There I recently created a website with dark mode and multi-language support for testing purposes, but I encountered an issue along the way. The Problematic Code I have removed any unnecessary elements from the code snippet below: portfolio/src/pag ...

Implementing dual language codes for a single locale in internationalization (i18n) efforts

I am currently using i18n to display translations in English and Japanese. The default language is set to English with the code en, but I have recently discovered that my website is not utilizing the correct ISO language code for Japanese, which should be ...

Tips for addressing style issues within innerText

I am trying to use PrismJS to highlight HTML code, but the inner text function doesn't recognize line breaks (\n). <pre class="language-markup background-code"><code [innerText]="getHtmlCode()""></code> I have been working wi ...

Debugger for Visual Code unable to locate URL in Microsoft Office Add-in

I recently installed the Microsoft Office Add-in Debugger VS code extension, but I'm having trouble getting it to work despite following the instructions. Every time I try, an error message pops up: Upon inspecting my launch.json file, I found this U ...