编辑路线说投射错误? (的NodeJS,expressjs,mongodb的)

时间:2018-06-07 16:53:54

标签: node.js express web-development-server

我正在网站上工作,我正在该网站上创建露营地。

每个人都可以通过提供他们的名字,链接和描述来发布他们的露营地。

在此之后,他们可以根据需要编辑和更新露营地。我正在将CRUD方法应用到露营地页面。

我遇到一个问题,当我添加一个编辑按钮然后点击它时,它会显示一个强制转换错误!

name: 'Bonfire Camping',
  image: 'https://images.unsplash.com/photo-1477512076069-d31eb021716f?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=f62c0b3e5084ad192dbc4fba9679a6cd&auto=format&fit=crop&w=600&q=60',
  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: 6 }
{ CastError: Cast to ObjectId failed for value "edit" at path "_id" for model "Campground"
    at MongooseError.CastError (/home/ubuntu/workspace/YelpCamp/v10/node_modules/mongoose/lib/error/cast.js:27:11)
    at ObjectId.cast (/home/ubuntu/workspace/YelpCamp/v10/node_modules/mongoose/lib/schema/objectid.js:158:13)
    at ObjectId.SchemaType.applySetters (/home/ubuntu/workspace/YelpCamp/v10/node_modules/mongoose/lib/schematype.js:724:12)
    at ObjectId.SchemaType._castForQuery (/home/ubuntu/workspace/YelpCamp/v10/node_modules/mongoose/lib/schematype.js:1095:15)
    at ObjectId.castForQuery (/home/ubuntu/workspace/YelpCamp/v10/node_modules/mongoose/lib/schema/objectid.js:198:15)
    at ObjectId.SchemaType.castForQueryWrapper (/home/ubuntu/workspace/YelpCamp/v10/node_modules/mongoose/lib/schematype.js:1064:15)
    at cast (/home/ubuntu/workspace/YelpCamp/v10/node_modules/mongoose/lib/cast.js:300:32)
    at Query.cast (/home/ubuntu/workspace/YelpCamp/v10/node_modules/mongoose/lib/query.js:3216:12)
    at Query._castConditions (/home/ubuntu/workspace/YelpCamp/v10/node_modules/mongoose/lib/query.js:1286:10)
    at Query._findOne (/home/ubuntu/workspace/YelpCamp/v10/node_modules/mongoose/lib/query.js:1502:8)
    at process.nextTick (/home/ubuntu/workspace/YelpCamp/v10/node_modules/kareem/index.js:315:33)
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
  message: 'Cast to ObjectId failed for value "edit" at path "_id" for model "Campground"',
  name: 'CastError',
  stringValue: '"edit"',
  kind: 'ObjectId',
  value: 'edit',
  path: '_id',
  reason: undefined,
  model: 
   { [Function: model]
     hooks: Kareem { _pres: [Object], _posts: [Object] },
     base: 
      Mongoose {
        connections: [Object],
        models: [Object],
        modelSchemas: [Object],
        options: [Object],
        _pluralize: [Function: pluralize],
        plugins: [Object] },
     modelName: 'Campground',
     model: [Function: model],
     db: 
      NativeConnection {
        base: [Object],
        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: [Object],
        name: 'yelp_camp_v6',
        '$initialConnection': [Object],
        db: [Object] },
     discriminators: undefined,
     '$appliedMethods': true,
     '$appliedHooks': true,
     schema: 
      Schema {
        obj: [Object],
        paths: [Object],
        aliases: {},
        subpaths: {},
        virtuals: [Object],
        singleNestedPaths: {},
        nested: [Object],
        inherits: {},
        callQueue: [],
        _indexes: [],
        methods: [Object],
        statics: {},
        tree: [Object],
        query: {},
        childSchemas: [],
        plugins: [Object],
        s: [Object],
        _userProvidedOptions: {},
        options: [Object],
        '$globalPluginsApplied': true,
        _requiredpaths: [],
        _indexedpaths: [] },
     collection: 
      NativeCollection {
        collection: [Object],
        opts: [Object],
        name: 'campgrounds',
        collectionName: 'campgrounds',
        conn: [Object],
        queue: [],
        buffer: false,
        emitter: [Object] },
     Query: { [Function] base: [Object] },
     '$__insertMany': [Function],
     '$init': Promise { [Object], catch: [Function] } } }

这是我的代码

//campground.js
    var express = require("express");
    var router  = express.Router();
    var Campground = require("../models/campground"),
          Comment    = require("../models/comment");
    //INDEX - show all campgrounds
    router.get("/", function(req, res){
        // Get all campgrounds from DB
        Campground.find({}, function(err, allCampgrounds){
           if(err){
               console.log(err);
           } else {
              res.render("campgrounds/index",{campgrounds:allCampgrounds});
           }
        });
    });

    //CREATE - add new campground to DB
    router.post("/",isLoggedIn, 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 author = {

                id:req.user._id,
                username:req.user.username

        }
        var newCampground = {name: name, image: image, description: desc , author:author}
        // Create a new campground and save to DB
        Campground.create(newCampground, function(err, newlyCreated){
            if(err){
                console.log(err);
            } else {
                //redirect back to campgrounds page
                console.log(newlyCreated);
                res.redirect("/campgrounds");
            }
        });
    });

    //NEW - show form to create new campground
    router.get("/new",isLoggedIn, function(req, res){
       res.render("campgrounds/new"); 
    });

    // SHOW - shows more info about one campground
    router.get("/: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});
            }
        });
    });

    //EDIT Campground Route
    router.get("/:id/edit", function(req,res){
        Campground.findById(req.params.id,function(err,foundCampground){
            if(err){
                res.redirect("/campgrounds");
            } else{
               res.render("campgrounds/edit",{campground:foundCampground}); 
            }
        })

    })

    //UPDATE campground Route
    router.put("/:id",function(req,res){
        Campground.findByIdAndUpdate(req.params.id,req.body.campground,function(err,updatedCampground){
            if(err){
                res.redirect("/campgrounds")
            } else{
                res.redirect("/campgrounds/" + req.params.id );
            }
        })
    })


    //middleware
    function isLoggedIn(req, res, next){
        if(req.isAuthenticated()){
            return next();
        }
        res.redirect("/login");
    }

    module.exports = router;

//show.ejs
<% include ../partials/header %>
<div class="container">
    <div class="row">
        <div class="col-md-3">
            <p class="lead">YelpCamp</p>
            <div class="list-group">
                <li class="list-group-item active">Info 1</li>
                <li class="list-group-item">Info 2</li>
                <li class="list-group-item">Info 3</li>
            </div>
        </div>
        <div class="col-md-9">
            <div class="thumbnail">
                <img class="img-responsive" src="<%= campground.image %>">
                <div class="caption-full">
                    <h4 class="pull-right">$9.00/night</h4>
                    <h4><a><%=campground.name%></a></h4>
                    <p><%= campground.description %></p>
                    <p>
                        <em>Submitted by <%= campground.author.username %></em>
                    </p>
                    <a class="btn btn-warning" href="/campgrounds/<% campground._id %>/edit">Edit</a>
                </div>
            </div>
            <div class="well">
                <div class="text-right">
                    <a class="btn btn-success" href="/campgrounds/<%= campground._id %>/comments/new">Add New Comment</a>
                </div>
                <hr>
                <% campground.comments.forEach(function(comment){ %>
                    <div class="row">
                        <div class="col-md-12">
                            <strong><%= comment.author.username %></strong>
                            <span class="pull-right">10 days ago</span>
                            <p>
                                <%= comment.text %> 
                            </p>
                        </div>
                    </div>
                <% }) %>
            </div>
        </div>
    </div>
</div>

<% include ../partials/footer %>

0 个答案:

没有答案
相关问题