【问题标题】:ValidationError: Product validation failed: age: Path `age` is required., first_name: Path `first_name` is requiredValidationError:产品验证失败:年龄:需要路径“年龄”。名字:需要路径“名字”
【发布时间】:2019-12-05 07:08:42
【问题描述】:

我是 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);


这是我发送的请求。

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

【问题讨论】:

    标签: node.js mongodb mongoose node-modules


    【解决方案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 作为键值对

    【讨论】:

    • 谢谢,这里出现错误 let newProduct = new Products() { first_name:req.body.Name, age:req.body.Age };年龄:.它在说“;”预计。
    • 谢谢你:),告诉你这可能是一件简单而愚蠢的事情:)
    • 摆脱了错误,但数据仍然没有保存在数据库中。空数据库在 Mongo 中创建。
    • 能不能试试console.log(err) 看看保存时有没有错误
    猜你喜欢
    • 2020-08-20
    • 2020-06-10
    • 1970-01-01
    • 2022-12-14
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多