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

"Trouble with Typescript's 'keyof' not recognizing 'any' as a constraint

These are the current definitions I have on hand: interface Action<T extends string, P> { type: T; payload: P; } type ActionDefinitions = { setNumber: number; setString: string; } type ActionCreator<A extends keyof ActionDefinitions> ...

Adding curly braces around values when using Angular's form group patchValue method

I have been working on a dynamic form using form builder in order to update form data dynamically. I have created a function that iterates through keys in an object and patches the form values based on matching key names. While this approach works for most ...

A guide to finding matching data in two collections with mongoose's aggregate method

My quiz application has two schemas: const quizSchema = new mongoose.Schema({ userID: { type: String, required: [true, 'User ID required'] } }); Response Schema - const responseSchema = new mongoose.Schema({ userID: { type: Str ...

I am struggling to locate the module '@next/env' in Next.js Vercel

After successfully developing a Next.js app on my local machine, I encountered an issue when trying to deploy it on Vercel - it kept giving me the error message Cannot find module '@next/env'. You can see the full error message here. I suspect t ...

Error message reading: "Invalid `p.account.findUnique()` call while attempting to sign in with oauth in Next-auth

Within my Next.js application, I have integrated next-auth for authentication using @next-auth/prisma-adapter with MySQL as the chosen database provider. However, when attempting to sign in via OAuth, an error has been encountered: https://next-auth.js.org ...

Challenges with Filtering in MongoDB

I can't seem to figure out what's going wrong with my code. I've checked the documentation and it all appears to be correct. I've also gone through several posts and attempted various solutions. Code: router.get('/rank/:rank' ...

Angular threw an error stating that it encountered an unexpected token 'var' when trying to declare a variable x as

Currently facing a challenge with my Angular application development. I have created a TS File that interacts with my API (imported in the index.html using a script tag) and exported some functions from this file to be used in my components. Despite everyt ...

Tips for relocating a route function to a separate JavaScript file within an Express.js application

I've been working on the code in my app.js file and it looks like this: var express = require('express'); var bodyParser = require('body-parser'); var mongoskin = require('mongoskin'); var routes = require('./route ...

Creating a realistic typewriter effect by incorporating Code Block as the input

I am looking to add a special touch to my website by showcasing a code segment with the Typewriter effect. I want this code block not only displayed but also "typed" out when the page loads. Unfortunately, I have been unable to find a suitable solution s ...

Leveraging updateMany and elemMatch with embedded schemas in mongoose for Node.js applications

My current challenge involves querying a MongoDB database with mongoose in order to update multiple fields within my database. The initial request seems to be correct as it does not trigger any errors, but I am encountering an issue with nested schemas whi ...

The AngularJS 2 TypeScript application has been permanently relocated

https://i.stack.imgur.com/I3RVr.png Every time I attempt to launch my application, it throws multiple errors: The first error message reads as follows: SyntaxError: class is a reserved identifier in the class thumbnail Here's the snippet of code ...

Navigating the waters of importing npm modules with typescript, gulp, and browserify is a skill

I'm facing challenges with performing some fundamental tasks such as importing packages that I installed using NPM. Despite conducting extensive research online and following various tutorials, I have been unable to achieve success. Here is my current ...

When trying to set the focus on the first item in a list using HTML and Angular, the focus unexpectedly shifts to the second

I've been tackling a UI requirement where the focus needs to be set on the first element of a list item constructed from an array of objects when the tab key is pressed for the first time. Subsequent tab key presses should cycle through the list items ...

What is the best way to develop a parent component tailored for individual pages in order to integrate react context within it?

I need to use a specific react context for certain pages in my project. Instead of creating the context in the root file app.js, I want to create it only for these specific pages. Is there a way to create a parent component (wrapper) that can be placed ar ...

What is the process for modifying object information using string input in typescript?

How can I update an object's value in TypeScript based on a string input related to the object key? const objData = { // random value A: 11, B: 13, C: 53, innerObj: { AStatus: true, BStatus: false, CStatus: true, }, }; type Item ...

Navigating the complexities of integrating Rollup, ES modules, TypeScript, and JSX can be a challenging endeavor due to

Lately, I've been learning about the tools mentioned in the title. However, I've encountered some bumps along the way, so I'm turning to StackOverflow for help. My Requirements I need something like Rollup to pack my stuff For bare module ...

Tips for ensuring the correct typing of a "handler" search for a "dispatcher" style function

Imagine having a structure like this: type TInfoGeneric<TType extends string, TValue> = { valueType: TType, value: TValue, // Correspond to valueType } To prevent redundancy, a type map is created to list the potential valueType and associate i ...

TypeScript requires that when explicitly specifying the return type of a generator, the `Generator.prototype.return` function must accept

I am utilizing a generator function to serve as a consumer for accumulating strings: function *concatStrings(): Generator<void, string, string> { let result = ''; try { while (true) { const data = yield; result += data; ...

Having trouble adding items to an array within a Javascript promise

I am facing an issue with the exported function in a Nextjs app, which acts as an API page. The problem arises when the 'domainnames' array returns nothing in the 200 response. Interestingly, if I exclude the 'GetDomainStatus()' funct ...

Error in Typescript: The identifier 'Proxy' is unknown

I'm trying to create a new variable using the Proxy type from the ES6 specification: myProxy: Proxy; However, I'm encountering the following error: Cannot find name 'Proxy'. Can anyone point me in the right direction to resolve th ...