首页 > 解决方案 > Mongoose - 接收 JSON 正文时出现“ValidationError:xxx:”

问题描述

我试图使用架构和路由器将新文档插入到我的集合中,如下所示:

SCHEMA

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const activitySchema = new Schema({
    date: { type: String, required: true},
    type: { type: String, required: true},
    text: { type: String, required: true},
    members: { type: String, required: true}
});

const Activity = mongoose.model('Activity', activitySchema);

module.exports = Activity;
ROUTER

router.route('/add').post((req, res) => {
    const dateP = req.body.date;
    const typeP = req.body.type;
    const textP = req.body.text;
    const membersP = req.body.members;
    const newActivity = new Activity({
        date: dateP,
        type: typeP,
        text: textP,
        members: membersP
    });

    newActivity.save()
        .then(() => res.json('Activity added!'))
        .catch(err => res.status(400).json('Error: ' + err));
});

但是当我通过 POSTMAN 发送 JSON 正文时,我收到以下错误:

"Error: ValidationError: date: Path `date` is required., type: Path `type` is required., text: Path `text` is required., members: Path `members` is required."

还有我的身体:

{
    "date": "2020-01-29",
    "type": "Night Course",
    "text": "Biology",
    "members": "Class 9a"
}

但是当我将 x-www-form-urlencoded 与 body-parser 包一起使用时,它可以工作。到底是怎么回事?为什么我无法从我的 JSON 文件中获取值?

编辑:这是我正在使用的正文解析器:

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(bodyParser.raw());

但是,只有 urlencoded 有效..

标签: node.jsjsonmongodbexpressmongoose

解决方案


如果我理解正确,如果你使用 body-parser 一切正常,如果你不使用它就不起作用。

如果是,您可能会从 Postman 获得值,但无论如何您都需要使用 body-parser。

body-parser 解析您的请求正文并通过 req.body 使其可用。因此,如果您不使用它,您的变量(dateP 等...)可能是未定义的,这可以解释为什么您会收到此错误。


推荐阅读