Mongoose发现回调函数执行if和else语句

时间:2018-02-12 01:17:27

标签: javascript node.js mongodb mongoose

我是mongoose和Node的新手,但这是我的页面显示一个露营地的路线。出于某种原因,findById的回调函数正在运行if和else语句。 所以我的代码可以找到正确的对象并在浏览器中显示它,但它似乎也返回了一个未定义的对象。

另外,当我在回调函数中使用console.log(camp.name)时,它会抛出一个错误并说它不能引用undefined的name属性...所以它似乎引用了一些未定义的对象,即使它确实找到了我正在寻找的对象。

app.get("/campgrounds/:id",function(req, res){
    var camp_Id = req.params.id;
    console.log("ID type: "+ typeof(camp_Id) + " | "+camp_Id);

    var camps = Campground.findById(camp_Id, function(err,camp){
        console.log(camp);

        if (err){
            console.log(err);
        }
        else{
            res.render("show", {camp:camp});
        }
    });
});

这是控制台输出:

ID type: string | 5a80c8c54d30a717de9121f4
{ _id: 5a80c8c54d30a717de9121f4,
  name: 'Fire Camp',
  image: 'https://images.unsplash.com/photo-1496379590766-6732d042fef5?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=65f8c4aa65a833e229c48dd9d3c2f12d&auto=format&fit=crop&w=1350&q=80',
  description: 'Fire and Camps and stuff. Best for smores.',
  __v: 0 }
ID type: string | campgrounds.js
undefined
{ CastError: Cast to ObjectId failed for value "campgrounds.js" at path "_id" for model "Campground"
    at MongooseError.CastError (/home/ec2-user/environment/YelpCamp/node_modules/mongoose/lib/error/cast.js:27:11)
    at ObjectId.cast (/home/ec2-user/environment/YelpCamp/node_modules/mongoose/lib/schema/objectid.js:158:13)
    at ObjectId.SchemaType.applySetters (/home/ec2-user/environment/YelpCamp/node_modules/mongoose/lib/schematype.js:701:12)
    at ObjectId.SchemaType._castForQuery (/home/ec2-user/environment/YelpCamp/node_modules/mongoose/lib/schematype.js:1072:15)
    at ObjectId.castForQuery (/home/ec2-user/environment/YelpCamp/node_modules/mongoose/lib/schema/objectid.js:198:15)
    at ObjectId.SchemaType.castForQueryWrapper (/home/ec2-user/environment/YelpCamp/node_modules/mongoose/lib/schematype.js:1041:15)
    at cast (/home/ec2-user/environment/YelpCamp/node_modules/mongoose/lib/cast.js:273:32)
    at Query.cast (/home/ec2-user/environment/YelpCamp/node_modules/mongoose/lib/query.js:3133:12)
    at Query._castConditions (/home/ec2-user/environment/YelpCamp/node_modules/mongoose/lib/query.js:1269:10)
    at Query._findOne (/home/ec2-user/environment/YelpCamp/node_modules/mongoose/lib/query.js:1485:8)
    at /home/ec2-user/environment/YelpCamp/node_modules/kareem/index.js:276:8
    at /home/ec2-user/environment/YelpCamp/node_modules/kareem/index.js:23:7
    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 "campgrounds.js" at path "_id" for model "Campground"',
  name: 'CastError',
  stringValue: '"campgrounds.js"',
  kind: 'ObjectId',
  value: 'campgrounds.js',
  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,
        hosts: null,
        host: 'localhost',
        port: 27017,
        user: null,
        pass: null,
        name: 'YelpCamp',
        options: null,
        otherDbs: [],
        states: [Object],
        _readyState: 1,
        _closeCalled: false,
        _hasOpened: true,
        _listening: false,
        _connectionOptions: [Object],
        '$initialConnection': [Object],
        db: [Object],
        client: [Object] },
     discriminators: undefined,
     '$appliedMethods': true,
     '$appliedHooks': true,
     schema: 
      Schema {
        obj: [Object],
        paths: [Object],
        aliases: {},
        subpaths: {},
        virtuals: [Object],
        singleNestedPaths: {},
        nested: {},
        inherits: {},
        callQueue: [],
        _indexes: [],
        methods: {},
        statics: {},
        tree: [Object],
        query: {},
        childSchemas: [],
        plugins: [Object],
        s: [Object],
        _userProvidedOptions: undefined,
        options: [Object],
        '$globalPluginsApplied': true,
        _requiredpaths: [] },
     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] } } }

编辑:以下是我的观点中的代码:campgrounds.ejs:

<% for(var i=0; i < camps.length; i++){     %>

            <div class = "col-md-4 col-sm-6">
                <a href="/campgrounds/<%=camps[i].id%>">
                <div class = "img-thumbnail">
                    <img class="img-fluid" src="<%=camps[i]["image"]%>" alt="<%=camps[i]["name"]%>">
                    <div class="caption text-center"><%= camps[i]["name"] %></div>
                </div>
                </a>
            </div>

        <%    };    %>

4 个答案:

答案 0 :(得分:0)

看起来你正在发出两个请求,一个是找到正确对象的“/ campgrounds / 5a80c8c54d30a717de9121f4”,另一个是返回undefined的“/campgrounds/campgrounds.js”。

答案 1 :(得分:0)

您的错误可能在您的视图中,只需查看ID的第二个日志:

ID type: string | campgrounds.js

之后猫鼬告诉你,当id campground.js 时它失败了:

'Cast to ObjectId failed for value "campgrounds.js" at path "_id"

您可能正在使用 campgrounds.js 作为ID拨打您的路线。

答案 2 :(得分:0)

应该从

更改
Campground.findById(camp_Id, function(err,camp){

Campground.findById(new mongoose.Types.ObjectId(camp_Id), function(err,camp){

答案 3 :(得分:0)

问题是您试图在此路由中传递:id。如果您有一条路线,例如“ campgrounds / xyz”,该路线位于“ campgrounds /:id”路线下。然后它将“ xyz”视为:id并尝试呈现此页面。

尝试在所有其他路线下放置“ campgroungs /:id”路线代码段,然后检查