typescript “错误:用户验证失败:name:路径`name`是必需的,”

5q4ezhmt  于 2023-08-07  发布在  TypeScript
关注(0)|答案(1)|浏览(123)

我正在使用mongoose和Next.js来制作我的应用程序的后端。我正在尝试创建一个推送函数,以便将新用户插入到我的数据库中。我刚开始使用mongoose,所以我不是很擅长,更不用说如何使用mongoose与typescript,但我试着按照文档所说的。我有用户作为主文档和捐赠作为子文档的用户。对于我的帖子请求,我试图只创建一个具有空捐赠数组的用户。

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

个字符
x1c 0d1x的数据
我从我的json请求中获取值,所以这不是问题。尝试运行User.create({ request values })时出现问题。我正在使用postman发出API请求。我有一些关于users. ts的错误。非常感谢您的帮助。

yqkkidmi

yqkkidmi1#

尝试将donations字段设置为可选字段:

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

字符串

相关问题