【问题标题】:Mongoose validation error while sending data using ExpressJS post route使用 ExpressJS 发布路由发送数据时出现 Mongoose 验证错误
【发布时间】:2018-04-28 09:11:34
【问题描述】:

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

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

如果我打印 req.body 它会打印所有具有正确值的字段,请参阅控制台输出: [ { controlType:'文本', 标签:'名称', 必需:假, 占位符:'名字'}]

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

【问题讨论】:

  • 在保存之前尝试打印 req.body.controlType。是否打印您发送的请求?
  • 如果我打印 req.body 它会打印所有具有正确值的字段,请参阅控制台输出:[ { controlType: 'text', label: 'name', required: false, placeholder: ' first name' } ] 但是当我使用 req.body.controlType 打印单个字段时,它会在控制台上打印 false 。我不知道为什么? @PavanVora

标签: node.js express mongoose mean-stack


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 2019-03-05
    • 2013-06-14
    • 2017-06-12
    • 2016-05-14
    • 2018-01-22
    相关资源
    最近更新 更多