ValidationError:产品验证失败:age:必需输入路径“ age”。first_name:必需输入路径“ first_name”

时间:2019-07-27 01:33:31

标签: node.js mongodb mongoose node-modules

我是Node.js的新手,我知道这是一个非常常见的问题,很多人都问过同样的问题。但是您知道在我的情况下没有任何解决方案有效。

请看一下代码,让我知道是否错过了一些事情

谢谢!

这是与Mongo db交互的node.js应用程序。

Product.controllers.js

const Products = require("../models/Product.models");

exports.Product_create = function(req, res, next){
    console.log(req.body.Name); //For test only - Here I am getting the values
    console.log(req.body.Age);  //For test only - Here I am getting the values
    let newProduct = new Products()
    {
        first_name = req.body.Name,
        age = req.body.Age
    };
    newProduct.save(function (err) {
        if (err) {
            return next(err);
        }
        res.send('Product Created successfully')
    })
};

exports.test = function(req, res){
    console.log("test controller reached successfully!");
};


Product.models.js

var mongoose = require("mongoose");
var schema = mongoose.Schema;

let ProductSchema = new schema({
    first_name : {type: String, required: true, max: 100},
    age: {type:Number, required: true}
});

//export model
module.exports = mongoose.model("Product", ProductSchema);


这是我发送的请求。 enter image description here

我在console.log(req.body.Name);console.log(req.body.Age);中收到正确的输出。但是它仍然不能保存数据。

1 个答案:

答案 0 :(得分:1)

错误在于您的产品初始化

const Products = require("../models/Product.models");

exports.Product_create = function(req, res, next){
    console.log(req.body.Name); //For test only - Here I am getting the values
    console.log(req.body.Age);  //For test only - Here I am getting the values
    let newProduct = new Products(
    {
        first_name:req.body.Name,
        age:req.body.Age
    });
    newProduct.save(function (err) {
        if (err) {
            return next(err);
        }
        res.send('Product Created successfully')
    })
};

exports.test = function(req, res){
    console.log("test controller reached successfully!");
};

您需要提供first_name and age作为键值对