使用ExpressJS路径发送数据时的Mongoose验证错误

时间:2017-11-15 08:16:52

标签: node.js express mongoose mean-stack

我正在开发一个Mean堆栈应用程序,我已经定义了一个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 ,它会打印所有具有正确值的字段,请参阅控制台输出: [{controlType:' text',     标签:' name',     必需:false,     占位符:'名字' }]

但是当我使用 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);

我的邮寄路线:

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;

1 个答案:

答案 0 :(得分:1)

看起来你的req.body正在返回和数组。尝试像req.body [0] .contentType这样的东西。我不确定,但你可以尝试一下。告诉我它是否解决了你的问题。