Node.js 猫鼬;验证错误:xxx:“;接收JSON正文时

Node.js 猫鼬;验证错误:xxx:“;接收JSON正文时,node.js,json,mongodb,express,mongoose,Node.js,Json,Mongodb,Express,Mongoose,我正试图使用schema和router将新文档插入我的收藏,如下所示: 模式 const mongoose=require('mongoose'); const Schema=mongoose.Schema; const activitySchema=新架构({ 日期:{type:String,必需:true}, 类型:{type:String,必需:true}, 文本:{type:String,必需:true}, 成员:{type:String,必需:true} }); const Activ

我正试图使用schema和router将新文档插入我的收藏,如下所示:

模式
const mongoose=require('mongoose');
const Schema=mongoose.Schema;
const activitySchema=新架构({
日期:{type:String,必需:true},
类型:{type:String,必需:true},
文本:{type:String,必需:true},
成员:{type:String,必需:true}
});
const Activity=mongoose.model('Activity',activitySchema);
module.exports=活动;
路由器
路由器.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=新活动({
日期:dateP,
类型:typeP,
text:textP,
成员:membersP
});
newActivity.save()
。然后(()=>res.json('Activity added!'))
.catch(err=>res.status(400).json('Error:'+err));
});
但当我通过邮递员发送JSON正文时,我得到以下错误:

“错误:验证错误:日期:路径`date`是必需的,类型:路径`type`是必需的,文本:路径`text`是必需的,成员:路径`members`是必需的。”
还有我的身体:

{
    "date": "2020-01-29",
    "type": "Night Course",
    "text": "Biology",
    "members": "Class 9a"
}
但当我使用x-www-form-urlencoded和body解析器包时,它是有效的。发生了什么事?为什么我不能从JSON文件中获取值

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

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

但是,仍然只有urlencoded可以工作。

如果我理解正确,如果使用主体解析器,一切都可以正常工作,如果不使用主体解析器,一切都不起作用

如果是,您可能会从Postman获得值,但无论如何都需要使用body解析器


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

在那里,我更新了我正在使用的body解析器。但仍然不适用于JSON。在我的路由器中,我使用所有占位符(dateP等)从每个req.body中检索值,这解释了为什么它使用urlencoded工作。在postman中,在body选项卡中,您是否选中“raw”并选择“JSON”?啊,是的,我忘了更改它。哎呀,谢谢你,原谅我的粗心。