Error: User authentication failed: username: `name` field is mandatory

While developing the backend of my app, I have integrated mongoose and Next.js. My current challenge is implementing a push function to add a new user to the database. As I am still relatively new to using mongoose, especially with typescript, I am following the documentation as closely as possible. In my schema setup, I have Users as the main document and Donations as a subdocument under Users. Specifically for my post request, my goal is to create a user with an empty donations array.

//users.ts

import mongoose, { Model, Schema, Types } from "mongoose";

interface IItem {
    name: string;
    condition: "poor" | "fair" | "good" | "very good";
}

// Subdocument Interface
interface IDonation {
    date: Date;
    address: string;
    items: Types.Array<IItem>;
}

// Document Interface
interface IUser {
    firstName: string;
    lastName: string;
    email: string;
    password: string;
    donations: IDonation[];
}

type UserDocumentProps = {
    donations: Types.DocumentArray<IDonation>;
};

type UserModelType = Model<IUser, {}, UserDocumentProps>;

// Create Model
// If already created, don't create again
export const User =
    mongoose.models.User ||
    mongoose.model<IUser, UserModelType>(
        "User",
        new Schema<IUser, UserModelType>(
            {
                firstName: String,
                lastName: String,
                email: String,
                password: String,
                donations: [
                    new Schema<IDonation>({
                        date: Date,
                        address: String,
                        items: [{ name: String, condition: String }],
                    }),
                ],
            },
            {
                timestamps: true,
            }
        )
    );

// api/users/route.ts

import { NextRequest, NextResponse } from "next/server";
import connectMongoDB from "../../../libs/mongodb";
import { User } from "../../../models/users";
import mongoose from "mongoose";

export async function POST(request: NextRequest) {
    const { firstName, lastName, email, password } = await request.json()
    console.log(firstName, lastName, email, password); // prints values
    if (mongoose.connection.readyState === 0) await connectMongoDB(); // if already connected, don't make new connection
    await User.create({ firstName, lastName, email, password }); // error occurs here
    return NextResponse.json({ message: "User Created" }, { status: 201 });
}

https://i.stack.imgur.com/i7kNW.png

Although I am successfully retrieving values from the json request, I encounter an issue when attempting to execute User.create({ request values }). This process is carried out using Postman for API requests. Any insights into potential issues related to users.ts would be greatly appreciated.

Answer №1

Consider allowing the contributions field to be optional:

export const User =
    mongoose.models.User ||
    mongoose.model<IUser, UserModelType>(
        'User',
        new Schema<IUser, UserModelType>(
            {
                firstName: String,
                lastName: String,
                email: String,
                password: String,
                contributions: {
                  type: [
                      new Schema<IContribution>({
                          date: Date,
                          address: String,
                          items: [{ name: String, condition: String }],
                      }),
                  ],
                  default: [],
                }
            },
            {
                timestamps: true,
            }
        )
    );

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

There was an issue with the deployment on Vercel as the build failed with the command "npm run build" exiting with a code of

Currently, I am in the process of developing a Next.js project that utilizes Firebase Authentication and database services. While everything functions properly on my local environment, I encounter an error message when attempting to host the project on any ...

Despite the unconsumedBufferLength being 0, DataReader.loadAsync is still being completed

Working on UWP WinRT, I'm dealing with JSON stream consumption using the following code: async function connect() { let stream: MSStream; return new CancellableContext<void>( async (context) => { stream ...

nodemon and ts-node not working as expected, failing to automatically recompile

I have been working on creating a REST API using express+ts-node. Following various online tutorials, I managed to set everything up and when I run the app using npm run dev, it works perfectly fine. However, I am facing an issue where it is not automatica ...

A guide on activating the <b-overlay> component when a child triggers an Axios request in vue.js

Is there a way to automatically activate the Bootstrap-vue overlay when any child element makes a request, such as using axios? I am looking for a solution that will trigger the overlay without manual intervention. <b-overlay> <child> ...

What is the reason for the disappearance of bullets on my Tailwind-styled <ul> items when overflow-scroll is added?

Currently, I am in the process of developing a website with react and tailwind. In one section of the page, I would like to incorporate a vertical scrollbar for a list. However, upon doing so, the bullets within the list disappear. This has left me puzzled ...

Organize information in a React table following a predetermined sequence, not based on alphabetical order

As a beginner with React, I'm looking to sort my data by the column "Status" in a specific order (B, A, C) and vice versa, not alphabetically. The data structure looks like this: export interface Delivery { id: number; name: string; amount: num ...

Error: You can't use the 'await' keyword in this context

I encountered a strange issue while using a CLI that reads the capacitor.config.ts file. Every time the CLI reads the file, it throws a "ReferenceError: await is not defined" error. Interestingly, I faced a similar error with Vite in the past but cannot ...

Is there a way to customize a chart in Ionic 2 to resemble the image provided?

Hello there, I am currently using import {Chart} from 'chart.js'; to generate my chart; however, I am facing some difficulties. My goal is to create a chart similar to the one displayed below. Warm regards //Generating the doughnut this.dou ...

Using ThreeJS in conjunction with NextJS requires that class constructors be called with the 'new' keyword

Seeking assistance with rendering a basic scene within a nextJS route named "lab2". Encountering the following error: Error: class constructors must be invoked with 'new' Call Stack: renderWithHooks mountIndeterminateComponent ...

Issue: The observer's callback function is not being triggered when utilizing the rxjs interval

Here is a method that I am using: export class PeriodicData { public checkForSthPeriodically(): Subscription { return Observable.interval(10000) .subscribe(() => { console.log('I AM CHECKING'); this.getData(); }); } ...

ReactJS: error occurs when trying to fetch data and encountering issues with reading properties

I am currently attempting to initiate an API call (a GET request) in order to download a document. However, I am encountering an error when making the API call: TypeError: Cannot read properties of undefined (reading 'payload') const printPin ...

What is the reason for the removal of the `?` decorator in this mapped type? Are there alternative methods to achieve a similar outcome without eliminating it

Challenge In the process of creating a mapped type that excludes properties of type Function, we encountered an issue. Our current method not only eliminates functions but also strips away the optional decorator (?) from the mapped properties. Scenario ...

Using TypeScript to destructure by providing types

I encountered an issue while trying to destructure some code. The error message Property 'name' does not exist on type '{}'. is appearing. I thought about using let user:any = {}; as a workaround, but that goes against the eslint rule o ...

Avoiding a full page crash due to a WebGLRenderer error: Unable to create WebGL context

Encountering a 3D project issue on a react/next site specifically in Chrome for certain users. The error message (THREE.WebGLRenderer: Error creating WebGL context.) leads to the entire page crashing, but only affecting some browsers and machines, consiste ...

Is it possible for the ionic ionViewDidEnter to differentiate between pop and setRoot operations?

I am facing an issue with my ionic 3 page where I need to refresh the data on the page only if it is entered via a navCtrl.setRoot() and not when returned to from a navCtrl.pop(). I have been using ionViewDidEnter() to identify when the page is entered, bu ...

What is the most efficient method for examining dependencies in Yarn 2 (berry)?

Is there a way to check for vulnerabilities in Yarn 2 dependencies? In Yarn 1.x, you could run yarn audit, similar to npm audit. However, this command is not available in Yarn 2. According to this issue on the Yarn berry Github, it may not be implemented ( ...

What steps can be taken to resolve the issue "AG Grid: Grid creation unsuccessful"?

For my project, I decided to use the modular import approach for AG-Grid. This means importing only the necessary modules instead of the entire package: "@ag-grid-community/core": "31.3.2", "@ag-grid-community/react": ...

To achieve this, my goal is to have the reels start playing on a separate page when a user clicks on the designated image. I am currently working on a project that involves this

When a user clicks on the designated image, I want the reels to start playing on a separate page. In my main project, I have a reels project within it, with the reels project built in ReactJS and the main project in React TypeScript. For example, if a user ...

Getting the data from the final day of every month in a Typescript time-series object array

I am dealing with timeseries data retrieved from an API that consists of random dates like the following: [ { "id": 1, "score": 23, "date": "2023-08-30" }, { "id": 2, "score&qu ...

Passing a function as a prop in a child component and invoking it in React using TypeScript

I have a function that I need to pass to a child component in order to manage the state in the parent component. The function takes an object declared in FriendListItem and adds it to an array as a new object. Despite my research efforts, I am struggling t ...