使用 ExpressJS post 路由发送数据时出现 Mongoose 验证错误

Mongoose validation error while sending data using ExpressJS post route

我正在开发一个 Mean stack 应用程序,我已经定义了一个 expressjs 后端 post 路由来在服务器上存储一些数据,但是它不起作用并且在字段上给出了 mongoose 验证错误,尽管我已经提供了所有字段。

message:"Path `controlType` is required."
name:"ValidatorError"
path:"controlType"
properties:{type: "required", message: "Path `{PATH}` is required.", path: "controlType"}
__proto__
:
Object

如果我打印 req.body 它会打印所有字段及其正确的值,请参阅控制台输出: [ { 控制类型: 'text', 标签:'name', 要求:假, 占位符:'first name' } ]

但是当我使用 req.body.controlType 打印单个字段时,它在控制台上打印 false。我不知道为什么? 它的猫鼬模式:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;    

var formSchema = new Schema({    
    controlType: {type: String, required: true},   
    label: {type: String, required: true},
    required: {type: Boolean}, 
    placeholder: {type: String},   
    options: [String],    //to store options for select or radio input
} ,  {collection: 'inputForm'});



module.exports = mongoose.model('Form', formSchema);

这是我的 post 路线:

const express = require('express');
const router = express.Router();
var Form = require('../../models/form');

/* GET api listing. */
router.get('/', (req, res) => {
  res.send('api works');
});

router.post('/userform', function (req, res, next) {
    console.log('in form api 0528');
    var keyName1=req.body;
    console.log(keyName1);

    var form = new Form({
        controlType: req.body.controlType,
        label: req.body.label,
        required:req.body.required ,        
        placeholder: req.body.placeholder,
        options: req.body.options
    });
    form.save(function(err, result) {
        if (err) {
            return res.status(500).json({
                title: 'An error occurred in form api 0528',
                error: err
            });
        }
        res.status(201).json({
            message: 'Form created',
            obj: result
        });
    });
});

module.exports = router;

看起来你的 req.body 正在返回数组。尝试类似 req.body[0].contentType 的内容。我不确定,但你可以试一试。告诉我它是否解决了您的问题。