尝试在发布路线上发表评论时出错

时间:2018-07-24 11:48:39

标签: node.js mongodb express

我是后端开发的新手,在发表评论时,控制台出现以下错误(我知道这段代码是一团糟,但在vs代码中看起来更好)

    { comments:
   [ { _id: 5b570970beff3674bc8e851d,
       text: 'This place is great, but I wish there was internet',
       author: 'Homer',
       __v: 0 } ],
  _id: 5b570970beff3674bc8e851a,
  name: 'Cloud\'s Rest',
  image: 'https://farm4.staticflickr.com/3795/10131087094_c1c0a1c859.jpg',
  description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum',
  __v: 1 }
{ CastError: Cast to ObjectId failed for value " 5b570970beff3674bc8e851a" at path "_id" for model "Campground"
    at new CastError (G:\webdevbootcamp\yelpcomp_project\node_modules\mongoose\lib\error\cast.js:29:11)
    at ObjectId.cast (G:\webdevbootcamp\yelpcomp_project\node_modules\mongoose\lib\schema\objectid.js:158:13)
    at ObjectId.SchemaType.applySetters (G:\webdevbootcamp\yelpcomp_project\node_modules\mongoose\lib\schematype.js:724:12)
    at ObjectId.SchemaType._castForQuery (G:\webdevbootcamp\yelpcomp_project\node_modules\mongoose\lib\schematype.js:1113:15)
    at ObjectId.SchemaType.castForQuery (G:\webdevbootcamp\yelpcomp_project\node_modules\mongoose\lib\schematype.js:1103:15)
    at ObjectId.SchemaType.castForQueryWrapper (G:\webdevbootcamp\yelpcomp_project\node_modules\mongoose\lib\schematype.js:1082:15)
    at cast (G:\webdevbootcamp\yelpcomp_project\node_modules\mongoose\lib\cast.js:303:32)
    at model.Query.Query.cast (G:\webdevbootcamp\yelpcomp_project\node_modules\mongoose\lib\query.js:3355:12)
    at model.Query.Query._castConditions (G:\webdevbootcamp\yelpcomp_project\node_modules\mongoose\lib\query.js:1327:10)
    at model.Query.Query._findOne (G:\webdevbootcamp\yelpcomp_project\node_modules\mongoose\lib\query.js:1552:8)
    at process.nextTick (G:\webdevbootcamp\yelpcomp_project\node_modules\kareem\index.js:333:33)
    at process._tickCallback (internal/process/next_tick.js:112:11)
  message: 'Cast to ObjectId failed for value " 5b570970beff3674bc8e851a" at path "_id" for model "Campground"',
  name: 'CastError',
  stringValue: '" 5b570970beff3674bc8e851a"',
  kind: 'ObjectId',
  value: ' 5b570970beff3674bc8e851a',
  path: '_id',
  reason: undefined,
  model:
   { [Function: model]
     hooks: Kareem { _pres: [Map], _posts: [Map] },
     base:
      Mongoose {
        connections: [Array],
        models: [Object],
        modelSchemas: [Object],
        options: [Object],
        _pluralize: [Function: pluralize],
        plugins: [Array] },
     modelName: 'Campground',
     model: [Function: model],
     db:
      NativeConnection {
        base: [Mongoose],
        collections: [Object],
        models: [Object],
        config: [Object],
        replica: false,
        options: null,
        otherDbs: [],
        relatedDbs: {},
        states: [Object],
        _readyState: 1,
        _closeCalled: false,
        _hasOpened: true,
        _listening: false,
        _connectionOptions: [Object],
        client: [MongoClient],
        name: 'yelp_camp',
        '$initialConnection': [Promise],
        db: [Db] },
     discriminators: undefined,
     '$appliedMethods': true,
     '$appliedHooks': true,
     schema:
      Schema {
        obj: [Object],
        paths: [Object],
        aliases: {},
        subpaths: [Object],
        virtuals: [Object],
        singleNestedPaths: {},
        nested: {},
        inherits: {},
        callQueue: [],
        _indexes: [],
        methods: {},
        methodOptions: {},
        statics: {},
        tree: [Object],
        query: {},
        childSchemas: [],
        plugins: [Array],
        s: [Object],
        _userProvidedOptions: {},
        options: [Object],
        '$globalPluginsApplied': true,
        _requiredpaths: [],
        _indexedpaths: [] },
     collection:
      NativeCollection {
        collection: [Collection],
        opts: [Object],
        name: 'campgrounds',
        collectionName: 'campgrounds',
        conn: [NativeConnection],
        queue: [],
        buffer: false,
        emitter: [EventEmitter] },
     Query: { [Function] base: [Query] },
     '$__insertMany': [Function],
     '$init': Promise { [Circular], catch: [Function] } } }

以下是我正在使用的文件

app.js

    var express = require("express"),
    app = express(),
    bodyParser = require("body-parser"),
    mongoose = require("mongoose"),
    Campground = require("./models/campgrounds"),
    Comment = require("./models/comment"),
    seedDB = require("./seeds")

mongoose.connect("mongodb://localhost/yelp_camp");
app.use(bodyParser.urlencoded({
    extended: true
}));
app.set("view engine", "ejs");
seedDB();

/*Campground.create(
    {
        name: "Granite Hill",
        image: "https://images.unsplash.com/photo-1445308394109-4ec2920981b1?ixlib=rb-0.3.5&s=73115e54fa3d099fcb2d92ccf12eee41&auto=format&fit=crop&w=1353&q=80",
        description: "This is a huge granite hill, no bathrooms, no water. Beautiful Granite!"
    },
    function(err,campground){
        if(err){
            console.log(err);
        } else {
            console.log("NEWLY CREATED CAMPGROUND: ");
            console.log(campground);
        }
    }
);  */

app.get("/", function (req, res) {
    res.render("landing");
});

//INDEX - show all campgrounds
app.get("/campgrounds", function (req, res) {
    //get all campgrounds from DB
    Campground.find({}, function (err, campgrounds) {
        if (err) {
            console.log(err);
        } else {
            res.render("campgrounds/index", {
                campgrounds: campgrounds
            });
        }
    });
});

app.get("/campgrounds/new", function (req, res) {
    res.render("campgrounds/new");
});

//post route for campgrounds
app.post("/campgrounds", function (req, res) {
    //get data from form and add to campgrounds array
    var name = req.body.name;
    var image = req.body.image;
    var desc = req.body.description;
    var newCampground = {
        name: name,
        image: image,
        description: desc
    }
    //create a new campground and save it to database
    Campground.create(newCampground, function (err, newlyCreated) {
        if (err) {
            console.log(err);
        } else {
            //redirect back to campgrounds page
            res.redirect("/campgrounds");
        }
    });
});

// SHOW - shows more info about one campground
app.get("/campgrounds/:id", function (req, res) {
    //find the campground with provided id
    Campground.findById(req.params.id).populate("comments").exec(function (err, foundCampground) {
        if (err) {
            console.log(err);
        } else {
            console.log(foundCampground);
            //render show template with that campground
            res.render("campgrounds/show", {
                campground: foundCampground
            });
        }
    });
});

    //===================================================
    //             ROUTES FOR COMMENTS
    //===================================================

    app.get("/campgrounds/:id/comments/new", function (req, res) {
        // find campgrounds by id
        Campground.findById(req.params.id, function (err, campground) {
            if (err) {
                console.log(err);
            } else {
                res.render("comments/new", {
                    campground: campground
                });
            }
        });
    });

app.post("/campgrounds/:id/comments", function (req, res) {
    //lookup campground using ID
    Campground.findById(req.params.id, function (err, campground) {
        if (err) {
            console.log(err);
            res.redirect("/campgrounds");
        } else {
            Comment.create(req.body.comment, function (err, comment) {
                if (err) {
                    console.log(err);
                } else {
                    campground.comments.push(comment);
                    campground.save();
                    res.redirect("/campgrounds/" + campground._id);
                }
            });
        }
    });
    //create new comment
    //connect new comment to campground
    //redirect to campground show page
});


//tell app to liten on local host
app.listen(3000, function () {
    console.log("yelpCamp server started");
});

视图>露营地> index.ejs

<% include ../partials/header %>

    <div class="container">
        <header class="jumbotron">
            <div class="container">
                <h1>Welcome to YelpCamp</h1>
                <p>view our hand-picked camp grounds from all over the world</p>
                <a class="btn btn-primary btn-lg" href="/campgrounds/new">Add New Campground</a>
            </div>
        </header>

        <div class="row">
            <div class="col-lg-12">
                <h3>Our Most Popular CampGrounds</h3>
            </div>
        </div>

        <div class="row text-center">
            <% campgrounds.forEach(function(campground){ %>
                <div class="col-md-3 col-sm-6">
                    <div class="thumbnail">
                        <img src="<%= campground.image %>" alt="">
                        <div class="caption">
                            <h4><%= campground.name %></h4>
                        </div>
                        <p>
                            <a href="/campgrounds/<%= campground._id %>" class="btn btn-primary">More Info</a>
                        </p>
                    </div>
                </div>
                <%}); %>
        </div>
    </div>

    <% include ../partials/footer %>

视图>露营地> new.ejs

<% include ../partials/header %>
    <div class="container">
    <div class="row">
        <h1 class="text-center">Create a New Campground</h1>
        <div style="width: 30%; margin: 25px auto;">
        <form action="/campgrounds" method="POST">
        <div class="form-group">
            <input class="form-control" type="text" name="name" placeholder="name">
        </div>
        <div class="form-group">
            <input class="form-control" type="text" name="image" placeholder="image url">
        </div>
        <div class="form-group">
            <input class="form-control" type="text" name="description" placeholder="description">
        </div>
            <button class="btn btn-primary btn-lg btn-block">Submit!</button>
        </form>
            <a href="/campgrounds">Go Back</a>
        </div>
        </div>
    </div>
    <% include ../partials/footer %>

视图>露营地> show.ejs

<% include ../partials/header %>

<h1>this is the show template</h1>
<p><%= campground.name %></p>
<img src="<%= campground.image %>">
<p><%= campground.description %></p>

<% campground.comments.forEach(function(comment){ %>
    <p>
    <strong><%= comment.author %></strong> - <%= comment.text %></p>
<% }) %>
<% include ../partials/footer %>

views> comments> new.ejs

   <% include ../partials/header %>
    <div class="container">
    <div class="row">
        <h1 class="text-center">Add New Comment to <%= campground.name %></h1>
        <div style="width: 30%; margin: 25px auto;">
        <form action="/campgrounds/ <%= campground._id %>/comments" method="POST">
        <div class="form-group">
            <input class="form-control" type="text" name="comments[text]" placeholder="text">
        </div>
        <div class="form-group">
            <input class="form-control" type="text" name="comments[author]" placeholder="author">
        </div>
            <button class="btn btn-primary btn-lg btn-block">Submit!</button>
        </form>
            <a href="/campgrounds">Go Back</a>
        </div>
        </div>
    </div>
    <% include ../partials/footer %>

尝试过的解决方案 -删除数据库并创建新数据库

更新:删除空间后,我被重定向到相应的露营地页面,但是它没有更新注释,并且出现了另一个错误,看起来像这样,请尝试解决它,但会有所帮助

{ comments:
   [ { _id: 5b571c8f30c81d36642d4aa6,
       text: 'This place is great, but I wish there was internet',
       author: 'Homer',
       __v: 0 } ],
  _id: 5b571c8f30c81d36642d4aa3,
  name: 'Cloud\'s Rest',
  image: 'https://farm4.staticflickr.com/3795/10131087094_c1c0a1c859.jpg',
  description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum',
  __v: 1 }
{ comments:
   [ { _id: 5b571c8f30c81d36642d4aa6,
       text: 'This place is great, but I wish there was internet',
       author: 'Homer',
       __v: 0 },
     { _id: 5b571cba30c81d36642d4aac, __v: 0 } ],
  _id: 5b571c8f30c81d36642d4aa3,
  name: 'Cloud\'s Rest',
  image: 'https://farm4.staticflickr.com/3795/10131087094_c1c0a1c859.jpg',
  description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum',
  __v: 2 } 

1 个答案:

答案 0 :(得分:0)

我认为您是在行中的露营地之后插入一个空格字符

<form action="/campgrounds/ <%= campground._id %>/comments" method="POST">

它甚至显示在stringValue: '" 5b570970beff3674bc8e851a"',

行中