尝试在 mlab 上向我的 mongoDB 写入新内容或更新时在 mongoose 中出现 ValidationError

Getting a ValidationError in mongoose when trying to write new or updates to my mongoDB on mlab

我一年多前建立的与旅行相关的小网站出现验证错误。我在创建最初的 post 时没有遇到任何问题,但现在在向站点添加任何内容的长时间中断之后,每当我尝试添加或编辑 post 时,我都会遇到错误。我唯一能想到的可能是 mongoose 或 MongoDB 或其他内容已更新。我只知道我对 webDev 的了解是从我在 Udemy 上观看全栈 webDev 课程时学到的,尽管内容丰富,但我只知道如何按照他们在课程中展示的方式做某事。 我搜索了很多,发现了很多关于 validationErrors 的问题,但是 none 的解决方案似乎解决了我遇到的问题,因为所有这些都是工作代码,而且自上次以来我的代码没有任何变化我使用该网站的时间。

这是我来自 Heroku 的错误日志:

Error [ValidationError]: Travel validation failed: tags: Cast to String failed for value "[ 'e' ]" at path "tags"
2020-01-29T04:49:40.091426+00:00 app[web.1]:     at ValidationError.inspect (/app/node_modules/mongoose/lib/error/validation.js:61:24)
2020-01-29T04:49:40.091429+00:00 app[web.1]:     at formatValue (internal/util/inspect.js:563:31)
2020-01-29T04:49:40.091432+00:00 app[web.1]:     at inspect (internal/util/inspect.js:221:10)
2020-01-29T04:49:40.091434+00:00 app[web.1]:     at formatWithOptions (internal/util/inspect.js:1693:40)
2020-01-29T04:49:40.091437+00:00 app[web.1]:     at Object.Console.<computed> (internal/console/constructor.js:272:10)
2020-01-29T04:49:40.091439+00:00 app[web.1]:     at Object.log (internal/console/constructor.js:282:61)
2020-01-29T04:49:40.091442+00:00 app[web.1]:     at /app/routes/travels.js:137:21
2020-01-29T04:49:40.091444+00:00 app[web.1]:     at /app/node_modules/mongoose/lib/utils.js:268:11
2020-01-29T04:49:40.091446+00:00 app[web.1]:     at /app/node_modules/mongoose/lib/model.js:4810:21
2020-01-29T04:49:40.091448+00:00 app[web.1]:     at _done (/app/node_modules/mongoose/lib/model.js:3101:16)
2020-01-29T04:49:40.091450+00:00 app[web.1]:     at /app/node_modules/mongoose/lib/model.js:3116:18
2020-01-29T04:49:40.091453+00:00 app[web.1]:     at callbackWrapper (/app/node_modules/mongoose/lib/model.js:3070:20)
2020-01-29T04:49:40.091455+00:00 app[web.1]:     at /app/node_modules/mongoose/lib/model.js:4791:16
2020-01-29T04:49:40.091456+00:00 app[web.1]:     at /app/node_modules/mongoose/lib/utils.js:268:11
2020-01-29T04:49:40.091458+00:00 app[web.1]:     at /app/node_modules/mongoose/lib/model.js:4810:21
2020-01-29T04:49:40.091459+00:00 app[web.1]:     at /app/node_modules/mongoose/lib/model.js:485:16 {
2020-01-29T04:49:40.091461+00:00 app[web.1]:   errors: {
2020-01-29T04:49:40.091463+00:00 app[web.1]:     tags: MongooseError [CastError]: Cast to String failed for value "[ 'e' ]" at path "tags"
2020-01-29T04:49:40.091464+00:00 app[web.1]:         at new CastError (/app/node_modules/mongoose/lib/error/cast.js:39:11)
2020-01-29T04:49:40.091466+00:00 app[web.1]:         at model.$set (/app/node_modules/mongoose/lib/document.js:1201:9)
2020-01-29T04:49:40.091467+00:00 app[web.1]:         at model._handleIndex (/app/node_modules/mongoose/lib/document.js:935:14)
2020-01-29T04:49:40.091469+00:00 app[web.1]:         at model.$set (/app/node_modules/mongoose/lib/document.js:879:22)
2020-01-29T04:49:40.091471+00:00 app[web.1]:         at model.Document (/app/node_modules/mongoose/lib/document.js:137:12)
2020-01-29T04:49:40.091473+00:00 app[web.1]:         at model.Model (/app/node_modules/mongoose/lib/model.js:102:12)
2020-01-29T04:49:40.091474+00:00 app[web.1]:         at new model (/app/node_modules/mongoose/lib/model.js:4611:15)
2020-01-29T04:49:40.091476+00:00 app[web.1]:         at /app/node_modules/mongoose/lib/model.js:3077:22
2020-01-29T04:49:40.091477+00:00 app[web.1]:         at /app/node_modules/mongoose/lib/model.js:3113:7
2020-01-29T04:49:40.091479+00:00 app[web.1]:         at Array.forEach (<anonymous>)
2020-01-29T04:49:40.091480+00:00 app[web.1]:         at /app/node_modules/mongoose/lib/model.js:3112:15
2020-01-29T04:49:40.091482+00:00 app[web.1]:         at Object.promiseOrCallback (/app/node_modules/mongoose/lib/utils.js:261:12)
2020-01-29T04:49:40.091483+00:00 app[web.1]:         at Function.create (/app/node_modules/mongoose/lib/model.js:3047:16)
2020-01-29T04:49:40.091485+00:00 app[web.1]:         at /app/routes/travels.js:135:12
2020-01-29T04:49:40.091493+00:00 app[web.1]:         at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
2020-01-29T04:49:40.091494+00:00 app[web.1]:         at next (/app/node_modules/express/lib/router/route.js:137:13) {
2020-01-29T04:49:40.091496+00:00 app[web.1]:       stringValue: `"[ 'e' ]"`,
2020-01-29T04:49:40.091497+00:00 app[web.1]:       kind: 'String',
2020-01-29T04:49:40.091499+00:00 app[web.1]:       value: [Array],
2020-01-29T04:49:40.091500+00:00 app[web.1]:       path: 'tags',
2020-01-29T04:49:40.091502+00:00 app[web.1]:       reason: [MongooseError],
2020-01-29T04:49:40.091503+00:00 app[web.1]:       message: `Cast to String failed for value "[ 'e' ]" at path "tags"`,
2020-01-29T04:49:40.091505+00:00 app[web.1]:       name: 'CastError'
2020-01-29T04:49:40.091506+00:00 app[web.1]:     }
2020-01-29T04:49:40.091507+00:00 app[web.1]:   },
2020-01-29T04:49:40.091509+00:00 app[web.1]:   _message: 'Travel validation failed',
2020-01-29T04:49:40.091511+00:00 app[web.1]:   name: 'ValidationError'
2020-01-29T04:49:40.091512+00:00 app[web.1]: }

这是我制作 "travel" 条目的架构:

var mongoose = require("mongoose");

var reviewPhoto = new mongoose.Schema({
    imgUrl: String,
    info:   String
});

var travelSchema = new mongoose.Schema({
    
    name:           String,
    category:       String,
    tags:           String,
    splashText:     String,
    body:           String,
    adRight:        String,
    photos: [ reviewPhoto ]
    
    }, { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' } }
);

module.exports = mongoose.model("Travel", travelSchema);

这是我的 ejs,其中包含我在创建新旅行时输入数据的旅行表格 post。有一种方法可以在网站上添加更多的评论照片,将额外的条目添加到照片数组中,但不包括该代码,因为它不应该是问题的任何部分:

<form action="/travel_new" method="POST">
                    <div id="reviewLeft">
                        <input type="text" name="travel[name]" placeholder="Travel Title" required>
                        <input type="text" name="travel[splashText]" placeholder="Splash Text" required>
                        <input type="text" name="travel[category]" placeholder="Category: ex: Park - Campground - Monument" required>
                        <input type="text" name="travel[tags]" id="tagField" placeholder="Tags - separate tags by a comma ex: sunset,national park,sky" required>
                        <input type="text" name="travel[adRight]" placeholder="need Ad Target url and the image Banner Url separated by comma ,  use none for no ad" required>
                        <textarea id="txDescription" name="travel[body]" placeholder='Start Article' required></textarea>
                        
                    </div>
                    
                    <div id="reviewRight" class="style-10">
                        <div class="border">
                            <input type="text" name="reviewPhoto[0][imgUrl]" placeholder="photo url" required>
                            <input type="text" name="reviewPhoto[0][info]" placeholder="photo Info" required>
                        </div>
                        
                    </div>
                    <input id="submitBtn" type="submit">
                </form>

这里是我的 node.js 服务器上用于 post 创建新旅行条目的代码:

router.post("/travel_new", isLoggedIn, function(req, res){

    var name     = req.body.travel.name;
    var category = req.body.travel.category || "default";
    var tags     = req.body.travel.tags;
    var splash   = req.body.travel.splashText;
    var body     = req.body.travel.body;
    var adRight  = req.body.travel.adRight  || "none";
    var photos   = req.body.reviewPhoto;
    
    tags = tags.split(",");
    
    //Assemble a variable to send all the review data into the create function for the SCHEMA pattern
    var newTravel = { name: name, category: category, tags: tags, splashText: splash, body: body, adRight: adRight, photos: photos };
    
    Travel.create( newTravel, function(err, travel){ 
        if(err){
            console.log(err);
            res.redirect("travel/new");
        }else{
            // console.log(travel);
            res.redirect("travel");
        }
    });
});

如果有帮助,这是我的 package.json 文件。

{
  "name": "travelSite",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "dependencies": {
    "body-parser": "^1.18.3",
    "ejs": "^2.6.1",
    "express": "^4.16.4",
    "express-session": "^1.15.6",
    "helmet": "^3.15.0",
    "method-override": "^3.0.0",
    "mongoose": "^5.3.12",
    "passport": "^0.4.0",
    "passport-local": "^1.0.0",
    "passport-local-mongoose": "^5.0.1"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app.js"
  },
  "author": "",
  "license": "ISC"
}

让我很困惑的是,网站上还有另一个区域,我可以在其中添加新照片,每张照片都有我输入的标题、描述和标签,而且它们都使用几乎相同的代码保存并更新到 mongoDB,网站的照片部分仍然可以正常工作。它只是添加旅行的区域。 所有这些都是同时编写的并且都有效,现在大约 9 个月后,只有网站的某些部分不起作用。 MongoDB 中已有的所有数据都可以很好地加载到网站上,所有已输入的行程都可以正常加载和显示,所以我知道连接到 [=67= 没有问题],也没有腐败。 错误消息似乎显示它正在尝试将数组转换为字符串,如果我记得的话,标签变量应该是一个字符串数组。 当编写 Web 代码不是您的实际工作,而是每 6 个月来来去去的爱好时,这就是问题所在。我忘记了大部分我学到的东西,每次我有时间写更多的网络代码时都必须重新学习很多东西。!

感谢您提供的任何帮助。

E

您在查询中将数组传递给 tags,该数组定义为 String 类型

因此,您的架构必须支持字符串数组,而不仅仅是字符串

在您的架构中进行此更改

var travelSchema = new mongoose.Schema({
name:           String,
category:       String,
tags:           [String],
splashText:     String,
body:           String,
adRight:        String,
photos: [ reviewPhoto ]
}, { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' } }
);