验证失败:路径为必填项即使我提供了所有必需的数据也会出错

问题描述 投票:0回答:1

我在 Nodejs 应用程序中使用 Mongoose,我想创建一个新的体验集合。为此,我在 Postman 中提供所有数据。我正在使用 application/x-www-form-urlencoded 发送我的数据。但我不断收到错误

“经验验证失败:experience.from:路径

experience.from
为必填项。,experience.company:路径
experience.company
为必填项。,experience.title:路径
experience.title
为必填项。”

一次又一次。我已经检查了我的架构和代码是否有任何拼写错误,但我似乎没有发现任何错误。我在许多网站上检查过此错误,但答案似乎总是拼写错误或“在架构中要求应设置为 false”。但我已将 required 设置为 true,因为我需要它。

这是我的架构

import mongoose from "mongoose";

const experienceSchema = new mongoose.Schema({
    experience: {
        user: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User",
        },
        title: {
            type: String,
            required: true,
        },
        company: {
            type: String,
            required: true,
        },
        location: String,
        from: {
            type: Date,
            required: true,
        },
        to: {
            type: Date,
        },
        current: {
            type: Boolean,
            default: false,
        },
        description: String,
    },
});

const Experience = mongoose.model("Experience", experienceSchema);

export default Experience;

这是我的体验路线文件

import express from "express";
import Profile from "../models/Profile.js";
import Experience from "../models/Experience.js";
import auth from "../middleware/auth.js";
import { body, validationResult } from "express-validator";

const router = express.Router();

// Create Experience
// Endpoint experience/
router.post(
    "/",
    auth,
    body("title", "Please provide your title").notEmpty().trim(),
    body("company", "Please provide your company name").notEmpty().trim(),
    body("location").trim(),
    body("from", "From date is required").notEmpty().trim(),
    body("to").trim(),
    body("current").isBoolean(),
    body("description").trim(),
    async (req, res) => {
        let profile = await Profile.findOne({ user: req.userid });
        if (!profile) {
            return res
                .status(400)
                .send("Profile does not exist! Please create a Profile.");
        }

        const result = validationResult(req);

        if (!result.isEmpty()) {
            return res.status(400).json({ errors: result.array() });
        }

        const { title, company, location, from, to, current, description } =
            req.body;

        try {
            const experienceFields = new Experience({
                title,
                company,
                location,
                from,
                to,
                current,
                description,
            });

            await experienceFields.save();

            return res.json(experienceFields);
        } catch (error) {
            console.error(error.message);
            res.status(500).send("Server Error...");
        }
    }
);

这是我的index.js 文件

import express from "express";
import connectDB from "./db.js";
import user from "./routes/user.js";
import auth from "./routes/auth.js";
import profile from "./routes/profile.js";
import experience from "./routes/experience.js";

const app = express();
const port = 3000;

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

app.use("/user", user);
app.use("/auth", auth);
app.use("/profile", profile);
app.use("/experience", experience);

app.listen(port, () => {
    console.log(`Listening on port ${port}`);
});

connectDB();

这是我在 Postman 中的数据图像 在此输入图片描述

我尝试将数据作为原始 json 发送并使用 json() 解析器作为中间件,但它一直给出相同的错误。

node.js mongodb validation mongoose postman
1个回答
0
投票

您的架构结构错误。

experience
模型有一个字段
experience
,结构为具有字段
user
title
等的对象,因此您的体验对象如下所示:

{
    "experience": {
        "user": {...},
        "title": "example title",
        "company": "example company"
        ...
    }
}

而不是:

{
    "user": {...},
    "title": "example title",
    "company": "example company"
    ...
}

您应该“展平”模式以删除包装

experience
对象:

const experienceSchema = new mongoose.Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
    },
    title: {
        type: String,
        required: true,
    },
    company: {
        type: String,
        required: true,
    },
    location: String,
    from: {
        type: Date,
        required: true,
    },
    to: {
        type: Date,
    },
    current: {
        type: Boolean,
        default: false,
    },
    description: String,
});

const Experience = mongoose.model("Experience", experienceSchema);

export default Experience;
© www.soinside.com 2019 - 2024. All rights reserved.