消息:路径是必需的

时间:2016-06-28 12:04:34

标签: node.js express mongoose mean-stack

您好我试图通过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文件的代码,但此时应用程序崩溃了,我想因为其他文件需要更新。 所以我被困在那里。

有谁理解为什么会这样?

提前致谢!

6 个答案:

答案 0 :(得分:4)

他兄弟..查看此图片..我也遇到了同样的问题..这就是我做错了。enter image description here

答案 1 :(得分:2)

我相信您的问题可能是未配置正文解析器。

尝试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

答案 2 :(得分:1)

ListBox

答案 3 :(得分:0)

事实上。如果,我改为:作者:“大妈妈”,评分:5,reviewText:“Lorem ipsum dolor amet”它完美无缺,但当我使用Postman在体内添加它时似乎是空的,我认为它应该管用。我正在使用x-www-form-urlencode,但尝试了所有其他选项。我想知道我应该如何在这里使用它...

答案 4 :(得分:0)

似乎已经排序了:我在review.push和working中添加了id创建功能。实际上我仍然没有理解为什么这是必要的,因为通常mongoose会在文档和子文档中添加ID,即使我在其他控制器上遇到问题,因为它添加了id&#39;不应该在哪里...这里是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!

答案 5 :(得分:0)

只需拨打一个 curl 电话-

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

enter image description here

2.然后发送POST请求