node.js - 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 有效..
解决方案
如果我理解正确,如果你使用 body-parser 一切正常,如果你不使用它就不起作用。
如果是,您可能会从 Postman 获得值,但无论如何您都需要使用 body-parser。
body-parser 解析您的请求正文并通过 req.body 使其可用。因此,如果您不使用它,您的变量(dateP 等...)可能是未定义的,这可以解释为什么您会收到此错误。
推荐阅读
- asp.net - 模型属性用 ASP.NET MVC 替换空间
- excel - 循环工作表并删除
- laravel - 我在 laravel 中的递归函数不调用自己
- jsonschema - 多阶段 $ref 不适用于 jsonschema 版本 3.0.1
- javascript - 事件侦听器似乎没有在侦听或获取必要/预期的值
- c# - 内容类型参数为 [] 时的模型状态验证错误
- reactjs - 如何将链接添加到传递给反应组件的文本部分?
- python - 运行 2 台服务器进行缓存是否很好?(Django 和 Node.js)
- asp.net - 在 ASP.NET MVC 中使用来自 SQL Server 的数据库值显示图形
- javascript - 任何点击后都不会立即加载预加载器