【问题标题】:message: path is required消息:路径是必需的
【发布时间】:2016-10-30 18:06:39
【问题描述】:

您好,我正在尝试通过 mongoose 创建一个新的子文档,但是当我在 Postman 中执行 POST 方法时收到以下消息:

{
  "message": "Location validation failed",
  "name": "ValidationError",
  "errors": {
    "reviews.1.reviewText": {
      "message": "Path `reviewText` is required.",
      "name": "ValidatorError",
      "properties": {
        "type": "required",
        "message": "Path `{PATH}` is required.",
        "path": "reviewText"
      },
      "kind": "required",
      "path": "reviewText"
    },
    "reviews.1.rating": {
      "message": "Path `rating` is required.",
      "name": "ValidatorError",
      "properties": {
        "type": "required",
        "message": "Path `{PATH}` is required.",
        "path": "rating"
      },
      "kind": "required",
      "path": "rating"
    },
    "reviews.1.author": {
      "message": "Path `author` is required.",
      "name": "ValidatorError",
      "properties": {
        "type": "required",
        "message": "Path `{PATH}` is required.",
        "path": "author"
      },
      "kind": "required",
      "path": "author"
    }
  }
}

这是我的位置数据库架构:

var mongoose = require('mongoose');

var reviewSchema = new mongoose.Schema({
    author: {type: String, required: true},
    rating: {type: Number, required: true, min: 0, max: 5},
    reviewText: {type: String, required: true},
    createdOn: {type: Date, "default": Date.now}
});

var openingTimeSchema = new mongoose.Schema({
    days: {type: String, required: true},
    opening: String,
    closing: String,
    closed: {type: Boolean, required: true}
});

var locationSchema = new mongoose.Schema({
    name: {type: String, required: true},
    address: String,
    rating: {type: Number, "default":0, min: 0,  max: 5},
    facilities: [String],
    coords: {type: [Number], index:'2ndsphere'},
    openingTimes: [openingTimeSchema],
    reviews: [reviewSchema]
});

mongoose.model('Location', locationSchema);

这里router.post('/locations/:locationid/reviews', ctrlReviews.reviewsCreate);下启动的控制器路由:

//reviews.js
var mongoose = require('mongoose');
var Loc = mongoose.model('Location');

module.exports.reviewsCreate = function (req, res) {
    var locationid = req.params.locationid;
    if(locationid){
        Loc
            .findById(locationid)
            .select('reviews')
            .exec(
                function(err, location){
                    if(err){
                        sendJsonResponse(res, 400, err);
                    } else{
                        console.log(location);
                        doAddReview(req, res, location);
                    }
                }
            );
    } else{
        sendJsonResponse(res, 400, {
            "message" : "Not found, locationid required"
        });
    }
};
// START - Functions for review create  //////////////////////////////////////
var doAddReview = function(req, res, location){
    if(!location){
        sendJsonResponse(res, 404, "locationid not found");
    } else{
        location.reviews.push({
            author: req.body.author,
            rating: req.body.rating,
            reviewText: req.body.reviewText
        });

        location.save(function(err, location){
            var thisReview;
            if(err){
                //sendJsonResponse(res, 400, err);
                sendJsonResponse(res, 400, err);
            } else{
                updateAverageRating(location._id);
                thisReview = location.reviews[location.reviews.length - 1];
                sendJsonResponse(res, 201, thisReview);
            }
        }); 
    }
};

var updateAverageRating = function(locationid){
    console.log("Update rating average for", locationid);
    Loc
        .findById(locationid)
        .select('reviews')
        .exec(
            function(err, location){
                if(!err){
                    doSetAverageRating(location);
                }
            }
        );
};

var doSetAverageRating = function(location){
    var i, reviewCount, ratingAverage, ratingTotal;
    if(location.reviews && location.reviews.length > 0){
        reviewCount = location.reviews.length;
        ratingTotal = 0;
        for(i=0; i<reviewCount; i++){
            ratingTotal = ratingTotal + location.reviews[i].rating;
        }
        ratingAverage = parseInt(ratingTotal / reviewCount, 10);
        location.rating = ratingAverage;
        location.save(function(err){
            if(err){
                console.log(err);
            } else{
                console.log("Average rating updated to", ratingAverage);
            }
        });
    }
};

我看到执行 location.save 函数时会弹出错误。我正在从一本书中学习 MEAN Stack,因此您可以在这里下载本章的完整代码:https://github.com/simonholmes/getting-MEAN/tree/chapter-06

我尝试从 app_api/controllers 文件夹中替换我的 locations.js 和 reviews.js 文件的代码,但此时应用程序崩溃了,我猜是因为其他文件需要更新所以。 所以我被困在那里。

有人知道为什么会这样吗?

提前致谢!

【问题讨论】:

    标签: node.js express mongoose mean-stack


    【解决方案1】:

    他兄弟..检查这张图片..我也面临同样的问题..这是我做错了。

    【讨论】:

    • 你是个救命的人
    【解决方案2】:

    我相信您的问题可能是未配置 body-parser。

    尝试 npm 安装 body-parser,然后将其导入主服务器文件的顶部:

    bodyParser = require('body-parser');
    

    最后,配置它以供使用。这将允许您使用 x-www-form-urlencoded:

    // Setting up basic middleware for all Express requests
    app.use(bodyParser.urlencoded({ extended: false })); // Parses urlencoded bodies
    app.use(bodyParser.json()); // Send JSON responses
    

    【讨论】:

    • 我之前遇到过类似的问题,解决了这个问题。
    • Joshua 我已经以这种方式配置了它,但我不会放弃这个问题来自一些解析错误,因为每次我安装一个模块时,我都会面临几个这样的警告:“npm WARN EJSONPARSE 无法解析 json”,也许这是相关的,但我找不到任何解决方案(缓存清除无法解决)。
    【解决方案3】:
    Check your 
    
        req.body.author,
        req.body.rating,
        req.body.reviewText
    
    
    They must be coming as empty string 
    

    【讨论】:

      【解决方案4】:

      事实上。如果,我将其更改为:作者:“Big Mama”,评分:5,reviewText:“Lorem ipsum dolor amet”它工作得很好,但是当我使用 Postman 在正文中添加它时,它似乎是空的,我认为它应该管用。我为此使用 x-www-form-urlencode,但尝试了所有其他选项。我想不明白我应该如何在这里使用它......

      【讨论】:

        【解决方案5】:

        似乎这是排序的:我在 review.push 中添加了 id 创建功能并且正在工作。真的,我仍然不明白为什么这是必要的,因为通常猫鼬将 id 添加到文档和子文档中,即使我在其他控制器上遇到问题,因为它在不应该的地方添加了 id...这里是 doAddReview 函数的更新代码对这个问题进行了排序:

        var doAddReview = function(req, res, location){
            if(!location){
                sendJsonResponse(res, 404, "locationid not found");
            } else{
                location.reviews.push({
                    _id: mongoose.Types.ObjectId(),
                    author: req.body.author,
                    rating: req.body.rating,
                    reviewText: req.body.reviewText
                    /*
                    author: "Big Mama",
                    rating: 5,
                    reviewText: "Lorem ipsum dolor amet"
                    */
                });
        
                location.save(function(err, location){
                    var thisReview;
                    if(err){
                        //sendJsonResponse("Error Here");
                        sendJsonResponse(res, 400, err);
                    } else{
                        updateAverageRating(location._id);
                        thisReview = location.reviews[location.reviews.length - 1];
                        sendJsonResponse(res, 201, thisReview);
                    }
                }); 
            }
        };
        

        非常感谢 Joshua 和 Piyush!

        【讨论】:

          【解决方案6】:

          只需打一个 curl 电话-

          1.首先将curl命令导入为Raw-text

          2.然后发送POST请求

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-01-17
            • 1970-01-01
            • 2019-06-01
            • 1970-01-01
            • 1970-01-01
            • 2022-10-14
            相关资源
            最近更新 更多